Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5, return 1->2->5.Given
1->1->1->2->3, return 2->3.
Solution:
这道题跟Remove Duplicates from Sorted List比较类似,只是这里要把出现重复的元素全部删除。其实道理还是一样,只是现在要把前驱指针指向上一个不重复的元素中,如果找到不重复元素,则把前驱指针指向该元素,否则删除此元素。算法只需要一遍扫描,时间复杂度是O(n),空间只需要几个辅助指针,是O(1)。
一般会改到链表头的题目就会需要一个辅助指针, 比如这里的newHead.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)
return null;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode pre = newHead;
ListNode cur = head;
while(cur != null) {
while(cur.next != null && pre.next.val == cur.next.val) {
cur = cur.next;
}
if(pre.next == cur) {
pre = pre.next;
}else {
pre.next = cur.next;
}
cur = cur.next;
}
return newHead.next;
}
}
No comments:
Post a Comment