LeetCode83- Remove Duplicates from Sorted List-Easy

删除链表中的重复结点:

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

解法一:

如果当前结点与它next结点值相同,那么就把当前结点的 next 指针跳过紧挨着的相同值的结点,指向后面一个结点(cur.next = cur.next.next),不移动当前指针。

如果当前结点与它next结点值不同,那么就向后移动指针。

/**
 * 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 cur = head;
        
        while(cur != null && cur.next != null) {
            if(cur.val == cur.next.val) {
                // 不移动cur
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        
        return head;
    }
}

解法二:

递归法

Base case:只有一个结点或空链表则返回头结点

对 head 后面的结点调用递归函数,那么就应该 suppose 返回来的链表就已经没有重复项了,此时接到 head 结点后面。

return检查head 和head.next 是否有duplicate。

/**
 * 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) {
        if(head == null || head.next == null) {
            return head;
        }
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
    }
}

猜你喜欢

转载自www.cnblogs.com/Jessiezyr/p/12963083.html
今日推荐