关闭

[leetcode] 83. Remove Duplicates from Sorted List

标签: leetcodeeasy
69人阅读 评论(0) 收藏 举报
分类:

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;
        
    }
};




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11661次
    • 积分:640
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类