关于leetcode:leetcode链表之删除排序链表中的重复元素

本文次要记录一下leetcode链表之删除排序链表中的反复元素

题目

给定一个排序链表,删除所有反复的元素,使得每个元素只呈现一次。

示例 1:

输出: 1->1->2
输入: 1->2

示例 2:

输出: 1->1->2->3->3
输入: 1->2->3

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cursor = head;
        ListNode next = head.next;
        while (next != null) {
            if (cursor.val == next.val) {
                cursor.next = next.next;
            } else {
                cursor = cursor.next;
            }
            next = next.next;
        }

        return head;
    }
}

小结

这里应用一个cursor,从head开始,再应用next保留失常遍历时的next,cursor在找到反复节点时批改next为next.next,否则后退一个节点

doc

  • remove-duplicates-from-sorted-list

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理