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>


  • 相关阅读:
    数组指针和指针数组
    C#反射机制
    浅探委托(delegate)和事件(event)
    C#的is和as操作符来进行强制类型转换&&值类型的拆箱、装箱
    2018-2-8
    JSP--语法
    JSP中的<%%>,<%! %>,<%= %>,<%-- --%>
    JSP--简介
    springmvc实现文件下载到Android手机设备pda端
    常用的正则表达式(转)
  • 原文地址:https://www.cnblogs.com/llguanli/p/6885681.html
Copyright © 2011-2022 走看看