[leetcode] 83. 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.

Solution:

Compare the value of current node to the value of next node. 

 /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return head;
        ListNode* cur = head;
        while (cur->next){
            if (cur->val != cur->next->val)
                cur = cur->next;
            else{
                cur->next = cur->next->next;
            }
        }
        return head;
        
    }
};




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51565244
文章标签: leetcode easy
个人分类: leetcode
上一篇[leetcode] 263. Ugly Number
下一篇[leetcode] 70. Climbing Stairs
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭