您的位置:首页 > 编程语言

编程实现双链表的建立、插入、删除、求长、逆置

2016-07-21 09:08 441 查看
#include <iostream>
#include <stdio.h>
#include <malloc.h>

using namespace std;

typedef struct node
{
int data;
struct node *next;
}node;

node *creat(){//单链表创建
node *head,*p,*s;
int x,cycle=1;
head=(node *)malloc(sizeof(node));
p=head;
while(cycle){
cout<<"please input the data:";
cin>>x;
if(x!=0){
s=(node *)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
}
else
cycle=0;
}
p->next=NULL;
p=head;
head=head->next;
free(p);
return head;
}

int length(node *head){//单链表测长
int n=0;
node *p=head;
while(p!=NULL){
p=p->next;
n++;
}
return n;
}

node *del(node *head, int num){//单链表删除
node *p1,*p2;
p1=head;
while(p1->data!=num&&p1->next!=NULL){
p2=p1;
p1=p1->next;
}
if(num==p1->data){
if(p1==head){
head=p1->next;
free(p1);
}
else{
p2->next=p1->next;
free(p1);
}
}
else
cout<<"can not find "<<num;
return head;
}

node *insert(node *head, int num){//插入链表--插入到第一个不小于num之后
node *p0,*p1,*p2;
p1=head;
p2=(node*)malloc(sizeof(node));
p2->data=num;
while(p2->data>p1->data&&p1->next!=NULL){
p0=p1;
p1=p1->next;
}
if(p2->data<=p1->data){
if(p1==head){
p2->next=head;
head=p2;
}
else{
p2->next=p1;
p0->next=p2;
}
}
else{
p2->next=NULL;
p1->next=p2;
}
return head;
}

node *reverse(node *head){//单链表的逆置
node *pre,*now;
pre=NULL;
now=head;
while(now!=NULL){
node *temp=now->next;
now->next=pre;
pre=now;
now=temp;
}
head=pre;
return head;
}

int main(){
node *head;
int n,del_num,insert_num;
head=creat();
cout<<"头结点数值:"<<head->data;
cout<<"\n delete_num:";
cin>>del_num;
head=del(head,del_num);
cout<<"头结点数值:"<<head->data;
cout<<"\n insert_num:";
cin>>insert_num;
head=insert(head,insert_num);
cout<<"头结点数值:"<<head->data;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: