zoukankan      html  css  js  c++  java
  • 83. Remove Duplicates from Sorted List java

    Given a sorted linked list, delete all duplicates such that each element appear only once.

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

    思路:定义两个指针,pre和cur,如果cur和pre相等,则cur移动;如果不相等,同时移动。

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
             if(head==null||head.next==null)//先判空
    		 return head;
    	 ListNode pre=head;//前指针
    	 ListNode cur=head.next;//后指针
    	 while(cur!=null)//后指针不为空
    	 {
    		 if(cur.val==pre.val)//相等,移动后指针,让pre.next=cur
    		 {
    			 pre.next=cur.next;
    			 cur=cur.next;
    		 }
    		 else//不相等,同时移动
    		 {
    			 pre=cur;
    			 cur=cur.next;
    		 }
    	 }
    	 return head;//最后直接返回head
        }
    }
    

      

  • 相关阅读:
    python函数
    文件操作
    python列表,元组,字典,集合简介
    python字符串(str)
    python数字类型 or 进制转换
    流程控制
    Python入门
    Python垃圾回收机制
    python简介&下载&安装
    DAY11
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6871734.html
Copyright © 2011-2022 走看看