83. Remove Duplicates from Sorted List
题目:
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
.
链接: http://leetcode.com/problems/remove-duplicates-from-sorted-list/
题解:
单链表去重复。 node.next.val与当前node.val相同时移动node.next,不同则移动当前node。 Time Complexity - O(n),Space Complexity - O(1)。
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return head; ListNode node = head; while(node.next != null){ if(node.next.val == node.val) node.next = node.next.next; else node = node.next; } return head; } }
二刷:
方法和一刷一样。
Java:
Time Complexity - O(n),Space Complexity - O(1)。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode node = head; while (node != null && node.next != null) { if (node.val == node.next.val) { node.next = node.next.next; } else { node = node.next; } } return head; } }
三刷:
Java:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode node = head;
while (node != null && node.next != null) { if (node.val == node.next.val) { node.next = node.next.next; } else { node = node.next; } } return head; } }