标签:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
思路:
较为简洁,遍历链表,遇到重复元素则将节点删除即可。编写上有一个可以注意的地方,链表节点将后节点与当前节点比较而非将当前节点与后节点进行比较,则会有比较方便的编写过程。
解法:
1 /* 2 public class ListNode 3 { 4 int val; 5 ListNode next; 6 7 ListNode(int x) 8 { 9 val = x; 10 } 11 } 12 */ 13 14 public class Solution 15 { 16 public ListNode deleteDuplicates(ListNode head) 17 { 18 if(head == null || head.next == null) 19 return head; 20 21 ListNode temp = head; 22 23 while(temp.next != null) 24 { 25 if(temp.next.val == temp.val) 26 temp.next = temp.next.next; 27 else 28 temp = temp.next; 29 } 30 31 return head; 32 } 33 }
LeetCode 83 Remove Duplicates from Sorted List
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5734343.html