题目链接:https://leetcode.com/problems/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.
解题思路:
这道题很简单,不做过多累述。
需要注意的是,每次更新 p 指针后都应该判断其是否已为空。为空直接跳出循环
代码实现:
/**
* 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)
return head;
ListNode p = head;
while(p.next != null) {
while(p.next != null && p.next.val == p.val)
p.next = p.next.next;
if(p.next != null)
p = p.next;
}
return head;
}
}
164 / 164 test cases passed.
Status: Accepted
Runtime: 1 ms