单链表的应用1(去重)
2016-04-03 19:01
369 查看
题目要求:在一个递增有序的线性表中,有数值相同的元素存在。若存储方式为单链表,设计算法去掉数值相同的元素,使表中不再有重复的元素。
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; typedef struct node { int data; struct node*next; } Linklist; Linklist* Create() { Linklist *head; head=(Linklist*)malloc(sizeof(Linklist)); if(head!=NULL) { head->next=NULL; return head; } else return NULL; } int InSert(Linklist *head,int e) { Linklist *p; Linklist *q=head; p=(Linklist*)malloc(sizeof(Linklist)); if(p!=NULL) { p->data=e; p->next=NULL; //cout<<"!!!"<<endl; while(q->next!=NULL) { q=q->next; } q->next=p; return 1; // if(head->next==NULL) // { // head->next=p; // return 1; // } // else // { // Linklist *q=head; // while(q!=NULL) // { // q=q->next; // } // q->next=p; // return 1; // } } return 0; } void DeletAgain(Linklist *head) { Linklist *p=head->next; Linklist *q=p->next; while(q!=NULL) { if(p->data == q->data) { Linklist *qq=q; q=q->next; p->next=q; free(qq); } else { p=p->next; q=q->next; } } } void Output(Linklist *head) { Linklist *p; p=head->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("\n"); } void FreeLink(Linklist *head) { Linklist *p,*q; p=head; q=NULL; while(p!=NULL) { q=p; p=p->next; free(q); } } int main() { struct node *head; int n; int e,flag=0; while(scanf("%d",&n)!=EOF) { if(n==-1) break; else { head=Create(); if(head!=NULL) { for(int i=0; i<n; i++) { scanf("%d",&e); flag=InSert(head,e); if(flag==0) { cout<<" Insert Fail "<<endl; break; } } if(flag==1) { Output(head); DeletAgain(head); Output(head); } if(flag==0) { cout<<" Insert Fail "<<endl; break; } FreeLink(head); } else { cout<<" Memory Full"<<endl; } } } return 0; }
相关文章推荐
- 金融风险和防范
- linux命令(二)arch命令
- OpenNLP进行中文命名实体识别(下:载入模型识别实体)
- CentOS 6.0找不到ifcfg-eth0解决方案
- Billboard
- 蚂蚁金服张洁:基于深度学习的支付宝人脸识别技术解秘-1
- 13.裸机程序和交叉编译工具链
- 两个集合的差
- 互联网公司GitHub repo 语言使用情况
- 20145320 《Java程序设计》第5周学习总结
- js+json实现ajax实例
- 《Linux内核与分析》第六周
- 229. Majority Element II
- 关于swift中函数的定义
- HTML 兼容性
- 关于Android studio 2.0beta5最近提示的Plugin is too old
- Neville算法
- Ubuntu14下cuda-7.5、tensorflow安装(enabling cuda 3.0)
- 在路上
- CentOS 6.5安装TortoiseSVN svn client