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

删除链表中的重复节点

时间:2015-06-28 17:08:48      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

这里的删除是只要有重复就要全部删除,如1->2->2->3,删除之后就是1->3.

#include<stdio.h>
#include<stdlib.h>

struct ListNode 
{
    int val;
    struct ListNode *next;
};

struct ListNode* deleteDuplicates(struct ListNode* head) 
{
    if(NULL==head||NULL==head->next)
        return head;
	struct ListNode** curNext = &head;//用来指向head 
    struct ListNode* cur = head;  
    while(NULL!=cur)  
    {  
        struct ListNode* temp=cur;  
        while(NULL!=cur->next && cur->next->val==cur->val)  
            cur = cur->next;  
        if(cur==temp)  
        {  
            *curNext=temp;  
            curNext=&(*curNext)->next;  
        }  
        cur=cur->next;  
    }  
    *curNext = NULL;  
    return head;  
}

int main()
{
	int i,n,tmp;
	while(scanf("%d",&n)!=EOF)
	{
		ListNode *head=(ListNode *)malloc(sizeof(ListNode));
		ListNode *p=head;
		head->next=NULL;
		for(i=0;i<n;i++)
		{
			scanf("%d",&tmp);
			ListNode *q=(ListNode *)malloc(sizeof(ListNode));
			q->val=tmp;
			p->next=q;
			p=q;
			p->next=NULL;
		}
		ListNode *r=deleteDuplicates(head->next);
		while(r)
		{
			printf("%d ",r->val);
			r=r->next;
		}
		printf("\n");
	}
	return 0;
}


删除链表中的重复节点

标签:

原文地址:http://blog.csdn.net/zyh920521/article/details/46672157

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