共计 727 个字符,预计需要花费 2 分钟才能阅读完成。
序
本文次要记录一下 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
正文完