zoukankan      html  css  js  c++  java
  • leetCode 82.Remove Duplicates from Sorted List II (删除排序链表的反复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.

    思路:这个题在刚開始做的时候想的有点,怎么都没办法正确解出。后面把代码所有删除重写。思路是记录当前节点p=head,然后head往下遍历,当head的值不等于head.next的值时,结束。比較p==head,相等说明没有反复,连接上。不相等说明有反复,跳过就可以。

    详细代码例如以下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
    
            ListNode first = new ListNode(0);
            ListNode last = first;
            
            ListNode p = head;
            
            while(head != null){
            	while(head.next != null){//p不动,head后移直到head.next与p不相等
            		if(p.val == head.next.val){
            			head = head.next;//相等循环
            		}else{
            			break;//不相等结束
            		}
            	}
            	if(p == head){//仅仅有一个
            		last.next = p;//加入
            		last = last.next;
            	}
            	p = head = head.next;//有多个则不加入
            	last.next = null;//去掉关联
            }
    		return first.next;
        }
    }



  • 相关阅读:
    PHP数组处理总结
    设计模式之-工厂模式理解
    我的世界观
    编程入门
    2019 新的一年
    placeholder 不支持ie8
    2018年8月20日
    HttpClientUtil
    通用mapper
    small_demo
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6950966.html
Copyright © 2011-2022 走看看