【Leetcode】【Easy】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.

 

解题思路:略

代码:

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

 

附录:

C++链表,申请和消除内存

posted @ 2014-12-01 23:10  胡潇  阅读(141)  评论(0编辑  收藏  举报