LinkedList - 83. Remove Duplicates from Sorted List
83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
思路:
这一题和26题移除数组中重复的元素一样都是去重,只不过这里的数据是链表,思路就是判断当前节点数值和下一个的节点值是否相同,如果相同就跳过下一个节点。不同就移动指针到下一个节点继续判断。
代码:
java:
/**
* 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 (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode explore = dummy.next;
while (explore != null && explore.next != null) {
if (explore.next.val == explore.val) explore.next = explore.next.next;
else explore = explore.next;
}
return dummy.next;
}
}