c链表实现

来源:互联网 发布:java实现建军照合成 编辑:程序博客网 时间:2024/04/29 14:56
#include <iostream>
using namespace std;


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






node* create()
{
node *head,*p,*s;
int x,cycle=1;
head = (node *)malloc(sizeof(node));
p = head;
while (cycle!=0)
{
cout<<"please input an interger: ";
cin>>x;
if (x!=0)
{
s = (node *)malloc(sizeof(node));
s->data = x;
p->next = s;
p = s;
}
else
{
cycle = 0;
p->next = NULL;
}
}
head = head->next;
return head;
}


int length(node* const head)
{
node* p;
int num=0;;
p = head;
if (head==NULL)
return 0;
while(p->next!=NULL)
{
num++;
p = p->next;
}
num++;
return num;
}




void print(node* const head)
{
node* p;
if (head == NULL)
{
cout<<"no list data"<<endl;
return;
}
p = head;
while (p->next!=NULL)
{
cout<<p->data<<endl;
p = p->next;
}
cout<<p->data<<endl;
}


node* del(node* head,int num)
{
node* p1,*p2;
p1 = head;
while(p1->next!=NULL && p1->data!=num)
{
p2 = p1;
p1 = p1->next;
}
if(p1->data==num)
{
if (p1==head)
{
head = p1->next;
free(p1);
}
else
{
p2->next = p1->next;
free(p1);
}
}
else
{
cout<<"cannot found num"<<endl;
}


return head;
}


node* insert(node* head,int num,int e)
{
int listlen = length(head);
if (num<0 || num>listlen)
{
cout<<"该位置不能插入"<<endl;
return head;
}
else
{
if (num==0)
{
node* p1 = (node*)malloc(sizeof(node));
p1->data = e;
p1->next = head;
head = p1;
return head;
}
else
{
int i = 1;
node *p,*p1;
p1 = head;
p = (node*)malloc(sizeof(node));
p->data = e;
p->next = NULL;
while(i<num)
{
p1 = p1->next;
i++;
}
p->next = p1->next;
p1->next = p;
return head;
}
}


}


node* reverse(node* head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node* p1,*p2,*p3;
p1 = head;
p2 = p1->next;
while(p2 != NULL)
{
p3 = p2->next;
p2->next=p1;
p1 = p2;
p2 = p3;
}
head->next = NULL;
head = p1;
return head;
}


int main()
{
node* head;
head = create();
cout<<length(head)<<endl;
print(head);
head = insert(head,length(head),20);
head = insert(head,0,10);
head = insert(head,2,19);
print(head);
head = reverse(head);
print(head);
return 0;
}
0 0
原创粉丝点击