flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3 

解答

 1 package LeetCode;
 2 
 3 /**
 4  * Definition for singly-linked list.
 5  * public class ListNode {
 6  *     int val;
 7  *     ListNode next;
 8  *     ListNode(int x) { val = x; }
 9  * }
10  */
11 public class L83_RemoveDuplicatesFromSortedList {
12     public ListNode deleteDuplicates(ListNode head) {
13         if(head==null)
14             return head;
15         ListNode cur=head;
16         //ListNode temp;
17         while(cur.next!=null){
18             if(cur.val!=cur.next.val)
19                 cur=cur.next;
20             else{
21                 /*temp=cur.next.next;
22                 cur.next=temp;*/
23                 cur.next=cur.next.next;
24             }
25         }
26         return head;
27     }
28 }

 

 

posted on 2018-10-29 22:23  flowingfog  阅读(117)  评论(0编辑  收藏  举报