标签:ret remove 统一 nod class 使用 The inpu null
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->5Example 2:
Input: 1->1->1->2->3
Output: 2->3
题目分析:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(-1); 取一个临时的节点指向head,方便后面删除head时候的处理
dummy.next = head;
// 找到删除的起点和终点
ListNode slow = dummy;
ListNode fast = dummy.next;
while (fast != null) {
// 找到下一个fast的位置,关键是fast.next.val != fast.val 同时注意,因为使用了fast.val 和fast.next.val 因此 fast 和 fast.next都不能为null
while (fast != null && fast.next != null && fast.next.val == fast.val) {
fast = fast.next;
}
if (slow.next != fast) { // fast和slow不相邻,说明中间有重复的元素
slow.next = fast.next;
fast = fast.next;
} else { // fast和slow相邻,说明中间没有重复元素
slow = slow.next;
fast = fast.next;
}
}
return dummy.next;
}
}
标签:ret remove 统一 nod class 使用 The inpu null
原文地址:https://www.cnblogs.com/isguoqiang/p/11532255.html