码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List leetcode

时间:2014-12-22 22:51:16      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.

题目意思为删除链表中重复的元素

思路: 遍历链表,用两个指针,一个指向前一个,一个指向后一个,当两个所指向的值不相等时,同时往后移,当两个指向的值相等时,需要删除一个元素(后一个指针指向的值),然后后一个往后遍历

代码如下:

<span style="font-size:18px;">/**
 * 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==NULL||head->next==NULL)
        return head; 
        
    ListNode *p,*q,*pur;
    
    p=head;
    
    q=p->next;
    while(q!=NULL)
    {
        if(p->val==q->val)
        {
            pur=q;
            q=q->next;
            p->next=q;
            delete pur;
        }
        else
        {
            p=q;
            q=q->next;
        }
    }
        
        return head;
        
    }
};</span>


Remove Duplicates from Sorted List leetcode

标签:leetcode

原文地址:http://blog.csdn.net/yujin753/article/details/42086741

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!