Remove Duplicates from Sorted List
Description:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Solution:
每次while循环,都判断当前节点与下一个节点的val是否一样,一样则改变当前节点的next指针,否则跳到下一个节点。
import java.util.*;
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head;
ListNode next;
while (temp != null) {
next = temp.next;
if (next == null)
break;
if (temp.val == next.val) {
temp.next = next.next;
} else {
temp = next;
}
}
return head;
}
}
Remove Duplicates from Sorted List II
Description:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Solution:
利用two pointer方法,每次对于当下要遍历的节点t1,都用进行另外一次遍历,记为t2,一直搜索到null或者t1和t2的val不同。如果t2是t1的next,那么就表示t1没有重复值,否则t1赋值到t2,继续遍历。
import java.util.*;
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode t1, t2;
t1 = head;
t2 = head;
while (t1 != null) {
t2 = t1;
while (t2 != null) {
if (t2.val != t1.val)
break;
t2 = t2.next;
}
if (t1.next == t2) {
break;
} else {
t1 = t2;
}
}
head = t1;
t1 = t2 = head;
ListNode temp = head;
while (t1 != null) {
t2 = t1;
while (t2 != null) {
if (t2.val != t1.val)
break;
t2 = t2.next;
}
if (t1.next == t2) {
temp.next = t1;
temp = temp.next;
System.out.println(temp.val);
t1.next = null;
t1 = t2;
} else {
t1 = t2;
}
}
return head;
}
}