Remove Duplicates from Sorted List | & ||
Remove Duplicates from Sorted List I
Given a sorted linked list, delete all duplicates such that each element appear only once.
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
分析:
Use one pointer called "current" to point to the head, and pointer "pointer" points to the next one. If the value of node pointed by "pointer" is the same with the value of the node pointed by pointer "current", we move pointer "pointer" to the next node, otherwise, current.next = pointer, and both pointers move to the next node.
1 /** 2 * Definition for ListNode 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param ListNode head is the head of the linked list 15 * @return: ListNode head of linked list 16 */ 17 public static ListNode deleteDuplicates(ListNode head) { 18 // write your code here 19 if (head == null || head.next == null) return head; 20 21 ListNode current = head; 22 ListNode pointer = head.next; 23 24 while (pointer != null) { 25 if (pointer.val != current.val) { 26 current.next = pointer; 27 current = pointer; 28 } 29 pointer = pointer.next; 30 } 31 current.next = null; 32 return head; 33 } 34 }
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
分析:
This question is a little bit hard. It is because we need to move the pointer all the way down to the node whose value is not the same with the previous one.
a if and while loop combination can be used in this case.
1 /** 2 * Definition for ListNode 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param ListNode head is the head of the linked list 15 * @return: ListNode head of the linked list 16 */ 17 18 public static ListNode deleteDuplicates(ListNode head) { 19 if (head == null || head.next == null) return head; 20 21 ListNode dummy = new ListNode(0); 22 ListNode current = dummy; 23 24 while (head != null) { 25 if (head.next != null && head.val == head.next.val) { 26 int val = head.val; 27 while(head != null && head.val == val) { 28 head = head.next; 29 } 30 } else { 31 current.next = head; 32 current = current.next; 33 head = head.next; 34 current.next = null; 35 } 36 } 37 return dummy.next; 38 } 39 }
转载请注明出处:cnblogs.com/beiyeqingteng/