1)每次重复的只要一次。
如果遇见相对了的直接跳过,跳到不等的地方。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
ListNode cur = head;
while(cur.next != null){
if(cur.next.val == cur.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
2)重复的全删除
找到相同节点的最后一个节点x,然后pre.next = x.next。就相当于把重复的元素全部删除了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
//怕第一个头节点就是重复节点,所以弄一个辅助节点排除特殊情况。返回的是helpNode.next就行。
ListNode helpNode = new ListNode(Integer.MAX_VALUE);
helpNode.next = head;
ListNode pre = helpNode;
ListNode cur = helpNode;
while(cur!=null){
while(cur.next != null && cur.next.val == cur.val){
cur = cur.next;
}//来到相同节点的最后一个相同节点。
cur = cur.next;
//此时的cur来到的位置是相同节点的下一个,也就是当前节点和前面的重复节点不一样,此时也需要判断一个当前节点和下一个节点是不是也是相同节点比如1->2->2->3->3,此时的cur就是第一个3
if(cur!=null && cur.next != null && cur.val == cur.next.val){
continue;//就是上面的一种情况,重复一遍,遇见相同的就重复。找到不同的。
}
//如果上面的3只有一次,那么就把pre.next的指针指向它
pre.next = cur;
pre = pre.next;
}
return helpNode.next;
}
}