【Leetcode】Remove Duplicates from Sorted List II

来源:互联网 发布:mac 沙盒路径 编辑:程序博客网 时间:2024/06/16 09:18

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

思路:

思路很简单,唯一要注意的是 删除操作加入头结点可以减少很多判断。

算法:

public ListNode deleteDuplicates(ListNode head) {if(head==null)return null;ListNode newHead = new ListNode(0);newHead.next = head;ListNode p = head, q, pre = newHead;// pre p qq = p.next;while (q != null) {if (p.val == q.val) {while (q != null && p.val == q.val) {// 如果节点相等则前移至后面第一个不等节点q = q.next;}pre.next = q;p = pre;//记得把p要更新,否则p指向的是要删除的结点,下次循环进入else会出错。p不能更新为q,否则下轮循环p/q相等进入死循环。} else {pre = p;p = q;q = q.next;}}return newHead.next;}

算法2:没加入头结点,简直超麻烦,判断边界条件神烦啊。。自从删除、增加结点操作加入头结点之后,代码简洁可读性强多了。亲身体会!


public ListNode deleteDuplicates(ListNode head) {ListNode p = head, q, pre = null;if (p == null) {return head;}// pre p qq = p.next;while (q != null) {if (p.val == q.val) {while (q != null && p.val == q.val) {// 如果节点相等则前移至第一个不等节点q = q.next;}if (pre == null) {// 如果头节点重复,需要特殊处理head = q;// 如此时1,1,2,2p = q;// head、p都指向2if (q != null) // 若不是1,1这种情况,即q为null时,q向前移到第二个2位置q = q.next;} else { //pre.next = q;p = pre;}} else {pre = p;p = q;q = q.next;}}return head;}




0 0
原创粉丝点击