LeetCode: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.

思路:遍历链表,通过两个指针保存当前位置和当前位置的前一个位置。假设两指针所指节点的值相等。则删除当前节点。假设不等。则将两指针前移。


代码:

 if(head == NULL)
        return NULL;
    ListNode * pre = head;
    ListNode * cur = head->next;
    while(cur != NULL)
    {
        if(pre->val == cur->val)
        {
            pre->next = cur->next;
            cur = cur->next;
        }
        else
        {
            pre = pre->next;
            cur = cur->next;
        }
    }


posted on 2017-04-27 12:50  ljbguanli  阅读(104)  评论(0编辑  收藏  举报