标签:
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
.
Solution:从排好序的链表中移除重复节点。
思路:
1)输入的是空链表;
2)由于是排好序的,因此重复元素只会接连出现,因此用两个指针遍历链表即可。
解决:
public static ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return null;
ListNode p = head; ListNode q = head.next; while(q != null) { if(p.val == q.val) { p.next = q.next; q = p.next; } else { p = q; q = p.next; } } return head; }
LeetCode--Remove Duplicates from Sorted List
标签:
原文地址:http://www.cnblogs.com/little-YTMM/p/4769739.html