删除链表中的重复节点

来源:互联网 发布:网络推广经理工作职责 编辑:程序博客网 时间:2024/05/16 14:04

这里的删除是只要有重复就要全部删除,如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;}


1 0
原创粉丝点击