Remove Duplicates from Sorted List
Med Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Thoughts
删除结点肯定需要记录下要被删的结点的next,所以新建next指针
Code
/**
* 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 node = head;
if (head == null || head.next == null) {
return head;
}
while (node != null && node.next != null) {
if (node.next.val == node.val) {
ListNode next = node.next.next;
node.next = next;
} else {
node = node.next;
}
}
return head;
}
}
Analysis
TC: O(n)
Last updated
Was this helpful?