zoukankan      html  css  js  c++  java
  • [LeetCode][Java] 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.

    题目:

    给定一个有序链表,删除全部反复的节点。剩余都是原链表中的不同样的节点元素。

    比方。

    给定1->2->3->3->4->4->5 。返回1->2->5.

    给定1->1->1->2->3 ,返回2->3.

    算法分析:

    设置前后双指针。后指针遇到反复元素就一直遍历直到反复的结尾,之后前指针指向后指针,这样就略过全部的反复元素。

    AC代码:

    <span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
    {
        public  ListNode deleteDuplicates( ListNode head) 
        {
            ListNode pre;
            ListNode cur;
            ListNode newhead = new ListNode(0);
            newhead.next=head;
            if(head==null||head.next==null)
            	return head;
            pre=newhead;
            cur=head;
            while(cur.next!=null)
            {
    	        if(cur.next.val==cur.val)//处理头几个元素同样的样例 如1 1 1 2 3 4 
    	        {
    	        	while(cur.next.val==cur.val)
    	        	{
    		        	cur=cur.next;
    		        	if(cur.next==null)//处理末尾几个元素同样的样例 1 2 3 4 5 5 5
    		        		break;
    	        	}
    		        pre.next=cur.next;
    		        //pre=pre.next;
    		        cur=cur.next;
    		        if(cur==null)
    		        	break;
    	        }
    	        else//处理头几个元素不同样的样例 1 2 3 4 5
    	        {
    	        	pre=pre.next;
    	        	cur=cur.next;
    	        }
    
            }
        	return newhead.next;
        }
    }</span>


  • 相关阅读:
    增量式爬虫 Scrapy-Rredis 详解及案例
    scrapy-redis使用以及剖析
    为什么代码要写到匿名自执行函数中?
    Vue组件第三天--webpack
    Vue组价通信
    Vue组件第一天
    pip3 install pycryptohome
    selenium 安装与 chromedriver安装
    解决:'chromedriver' executable needs to be in PATH问题
    如何在VS Code中编写Python
  • 原文地址:https://www.cnblogs.com/llguanli/p/6885681.html
Copyright © 2011-2022 走看看