本文次要记录一下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