删除链表中的反复节点
这里的删除是仅仅要有反复就要所有删除,如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; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步