老早就想自己写写链表的基本操作的实现,
写写来练练手。
#include<iostream>
#include<cstring>
#include<conio.h>
using namespace std;
typedef struct Node{
int data;
struct Node *next;
}node;
//链表的建立
node *CreateList(int n)
{
node *p1,*p2;
node *head;
int x=1;
head=(node*)malloc(sizeof(node));
p1=head;
while(n--)
{
p2=(node*)malloc(sizeof(node));
p2->data =x++;
p1->next =p2;
p1=p2;
}
head=head->next;//第一个有数据的给头指针;
p1->next=NULL;
return head;
}
//链表的测长
int Length(node *head)
{
int len=0;
node *p1=head;
while(p1!=NULL)
{
p1=p1->next ;
len++;
}
return len;
}
//链表的打印
void ListPrintf(node *head)
{
node *p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next ;
}
}
//链表反转
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;
}
//链表删除;删除第n个节点
node *DeleteNode(node *head,int n)
{
int len=Length(head);
if(n>len)
return head;
node *p1=head;
node *p2;
p2=p1->next ;
int m=1;
while(p2!=NULL)
{
p2=p1->next ;
m++;
if(m==n)
{
p1->next =p2->next ;
free(p2);
break;
}
p1=p2;
}
return head;
}
//链表删除;删除数据与num相等的节点,或没有此节点;
node *DeleteList2(node *head,int num)
{
node *p1,*p2;
p1=head;
while(num!=p1->data &&p1->next !=NULL)
{
p2=p1;
p1=p1->next ;
}
if(num==p1->data )
{
if(p1==head)
{
head=head->next ;
free(p1);
}
else
{
p2->next =p1->next ;
free(p1);
}
}
else
{
cout<<"can not find the node.";
}
return head;
}
// 链表的插入;链表是顺序排列的;并没有要求输入要插入的位置;输入插入的数据;
node *InsertNode(node *head,int loc)
{
node *p1,*p2,*p0;
p1=head;
p0=(node*)malloc(sizeof(node));
p0->data =loc;
while(p0->data >p1->data &&p1->next !=NULL)
{
p2=p1;
p1=p1->next ;
}
if(p0->data <=p1->data )
{
if(p1==head) //查到头部;
{
p0->next =head;
head=p0;
}
else
{
p2->next =p0;
p0->next =p1;
}
}
else //插到尾部;
{
p1->next =p0;
p0->next =NULL;
}
return head;
}
int main()
{
node *head;
int n=10;
int del_num;
int insert_num;
int num=6;
head=CreateList(n);
ListPrintf(head);
cout<<endl;
head=DeleteList2(head, num);
ListPrintf(head);
cout<<endl;
head=Reverse(head);
ListPrintf(head);
cout<<endl;
head=Reverse(head);
ListPrintf(head);
cout<<"\n del_num:";
cin>>del_num;
head=DeleteNode(head,del_num);
ListPrintf(head);
cout<<"\n insert_num:";
cin>>insert_num;
head=InsertNode(head,insert_num);
ListPrintf(head);
return 0;
}