首页 > 其他 > 详细

LeetCode83- Remove Duplicates from Sorted List-Easy

时间:2020-05-26 09:20:08      阅读:58      评论:0      收藏:0      [点我收藏+]

删除链表中的重复结点:

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;
    }
}

 

LeetCode83- Remove Duplicates from Sorted List-Easy

原文:https://www.cnblogs.com/Jessiezyr/p/12963083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!