题目描述:
题目思路:
1.链表内的val是递增的,所以相同的值只会连续重复地出现。
2.设置三个指针:
①指向头结点指针,用于返回链表
②指向返回链表链尾的指针,用于在新链表添加结点
③遍历旧链表结点的指针
3.要注意参考对比值变量的更新和②③指针的更新
代码实现:
import java.util.*;/** public class ListNode {* int val;* ListNode next = null;* public ListNode(int val) {* this.val = val;* }* }*/public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param head ListNode类 * @return ListNode类*/public ListNode removeDuplicates (ListNode head) {// write code here//首先看清楚这是一个递增的链表ListNode prehead=new ListNode(-1);ListNode firstPointer=prehead;ListNode movePointer=head;//向后遍历指针if(head!=null){int nowval=head.val;firstPointer.next=head;firstPointer=firstPointer.next;while(movePointer.next!=null){if(nowval!=movePointer.next.val){firstPointer.next=movePointer.next;firstPointer=firstPointer.next;//更新nowvalnowval=movePointer.next.val;}movePointer=movePointer.next;}firstPointer.next=null;return prehead.next;}else{return head;}}
}
刷题链接:
牛牛的递增之旅_牛客题霸_牛客网