题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
解题思路:从前往后遍历节点,如果当前节点和下一个节点的值相等,就跳过下一个节点
具体算法如下:
- current = head
- 如果 current!=null && current.next !=null,则循环执行:
- 循环删除后续重复节点:如果 current.next!=null && current.val == current.next.val,说明当前节点和下一个节点重复了,删除下一个节点,令current.next = current.next.next
- current = current.next
AC代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current!=null&¤t.next!=null){
while (current.next!=null&¤t.val==current.next.val){
current.next =current.next.next;
}
current=current.next;
}
return head;
}
}