LeetCode 83. Remove Duplicates from Sorted List

原题链接在这里:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目:

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.

题解:

Time Complexity: O(n), n是list长度. Space: O(1).

AC Java:

 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         if(head == null || head.next == null){
12             return head;
13         }
14         ListNode cur = head;
15         while(cur.next != null){
16             if(cur.val == cur.next.val){
17                 cur.next = cur.next.next;
18             }else{
19                 cur = cur.next;
20             }
21         }
22         return head;
23     }
24 }

AC C++:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* deleteDuplicates(ListNode* head) {
14         if(!head || !head->next){
15             return head;
16         }
17 
18         ListNode* it = head;
19         while(it->next){
20             if(it->val == it->next->val){
21                 it->next = it->next->next;
22             }else{
23                 it = it->next;
24             }
25         }
26 
27         return head;
28     }
29 };

跟上Remove Duplicates from Sorted List IIRemove Duplicates from Sorted Array.

posted @ 2015-09-02 12:19  Dylan_Java_NYC  阅读(274)  评论(0编辑  收藏  举报