82. Remove Duplicates from Sorted List II

39次阅读

共计 889 个字符,预计需要花费 3 分钟才能阅读完成。

Given a sorted linked list, delete all nodes that have duplicatenumbers, leaving only distinct numbers from the original list.
https://leetcode.com/problems…
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# Two nodes: one to keep head, one to keep tail.
ahead = phead = ListNode(‘null’)

# Two pointers: one to move ahead, one to monitor duplicates.
p = None
c = head

# When move to end, terminate.
while c:
# At the beginning, simple move one step forward.
if p == None:
p = c
# If p and c have different values, need to determine why.
elif p.val != c.val:
# If p and c are neighbors, p must be unique value.
if p.next == c:
phead.next = p
phead = phead.next
phead.next = None
# p gets one step forward.
p = c
# If p and c are not neighbors, ignore nodes with p.val.
else:
p = c
# c moves one step anyway.
c = c.next

# If p is not None (input not empty) and has next, collect last element.
if p != None and p.next == None:
phead.next = p

return ahead.next

正文完
 0

82. Remove Duplicates from Sorted List II

39次阅读

共计 894 个字符,预计需要花费 3 分钟才能阅读完成。

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3

难度:medium
题目:给出一排序链表,删除所有重复结点,只保留原链表中不重复的结点。
思路:双指针遍历
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.Memory Usage: 37.8 MB, less than 0.94% of Java online submissions for Remove Duplicates from Sorted List II.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {val = x;}
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (null == head) {
return head;
}

ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode prev = dummyHead, ptr = head;
while (ptr != null && ptr.next != null) {
if (ptr.val == ptr.next.val) {
while (ptr.next != null && ptr.val == ptr.next.val) {
ptr = ptr.next;
}
prev.next = ptr.next;
ptr = prev;
}
prev = ptr;
ptr = ptr.next;
}

return dummyHead.next;
}
}

正文完
 0