【Leetcode】83. Remove Duplicates from Sorted List
Question:
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
.
Tips:将一个有序链表中的重复val的结点删除。
思路:
设置一个指针,当指针下一个结点的val值与当前指针val相等就指针指向下一个结点的下一个。
cur.next=cur.next.next;
代码:
public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; ListNode cur = head; while (cur != null) { if(cur.next!=null){ if (cur.val == cur.next.val) { cur.next=cur.next.next; }else{ cur=cur.next; } }else break; } return head; }
递归:
public ListNode deleteDuplicates2(ListNode head) { if (head == null || head.next == null) return head; head.next =deleteDuplicates2(head.next); return head.val==head.next.val?head.next:head; }