题目:
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
.
类似单链表的遍历。需要注意一点:仅当下个节点和当前节点值不一样时,才跳到下一个节点!!
代码:(顺便吐槽下,这么简单的题提交了3次才AC,链表操作里的细节要格外留意啊)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode ret = head;
while (head != null && head.next != null) {
int currentVal = head.val;
int nextVal = head.next.val;
if (currentVal == nextVal)
head.next = head.next.next;
else
head = head.next;
}
return ret;
}
}