leetcode--Remove Duplicates from Sorted List

来源:互联网 发布:网天概预算软件 编辑:程序博客网 时间:2024/06/03 14:42

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.

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode deleteDuplicates(ListNode head) {  
  11.         ListNode h = new ListNode(Integer.MAX_VALUE);  
  12.         h.next = head;  
  13.         ListNode pre = h;  
  14.         ListNode cur = head;  
  15.         while(cur!=null){  
  16.             if(pre.val==cur.val){  
  17.                 pre.next = cur.next;                  
  18.             }else{  
  19.                 pre = cur;                
  20.             }  
  21.             cur = cur.next;  
  22.         }  
  23.         return head;  
  24.     }  
  25. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46377149

原创粉丝点击