1. 程式人生 > >C語言中單鏈表的一些操作

C語言中單鏈表的一些操作

#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
/*定義節點*/
struct node
{
int data;
struct node *next;
};
/*建立新節點*/
struct node *create_node(int num)
{
struct node *p=(struct node*)malloc(sizeof(struct node));//給結點分配空間;
if(p==NULL)
{
printf("create error\n");
}
bzero(p,sizeof(struct node));//清理堆空間
p->data=num;
p->next=NULL;
return p;
}
/*頭插*/
struct node *insert_head(struct node *pheader,struct node *new)
{
struct node *p=pheader;
new->next=p->next;
p->next=new;
}
/*中間插入*/
struct node *insert_index(struct node *pheader,struct node *new,int num)
{
struct node *p=pheader;
int count=0;
if(p->next==NULL)
{
printf("連結串列為空\n");
}
while(p->next!=NULL)
{
p=p->next;
count++;
if(count==num)
{
new->next=p->next;
p->next=new;
break;
}
}
}
/*尾插*/
struct node *insert_tail(struct node *pheader,struct node *new)
{
struct node *p=pheader;
while(p->next!=NULL)
{
p=p->next;
}
p->next=new;
}
/*逆序*/
int reserve(struct node *pheader)
{
struct node *p=pheader;
struct node *p1=NULL;
struct node *p2=NULL;
struct node *p3=NULL;
if(p->next==NULL)
{
printf("連結串列為空\n");
return -1;
}
if(p->next->next==NULL)
{
printf("連結串列僅有一個有效節點\n");
return -1;
}
p1=p->next;
p2=p->next->next;
p3=p->next->next->next;
while(p3!=NULL)
{
p2->next=p1;
p1=p2;
p2=p3;
p3=p3->next;
}
p2->next=p1;
p->next->next=NULL;
    p->next=p2;
}
/*刪除*/
int delate(struct node *pheader,int num)
{
struct node *p=pheader;
struct node *pprev=NULL;
int flag=0;
if(p->next==NULL)
{
printf("連結串列為空\n");
}
while(p->next!=NULL)
{
pprev=p;
p=p->next;
if(p->data==num)
{
pprev->next=p->next;
free(p);              //釋放被刪的節點的空間
}
flag=1;
}
if(flag==0)
{
printf("沒有要刪除的數\n");
return -1;
}
}
/*顯示*/
int display(struct node *pheader)
{
struct node *p=pheader;
if(p->next==NULL)
{
printf("連結串列為空\n");
return -1;
}
while(p->next!=NULL)
{
p=p->next;
printf("p->data=%d\n",p->data);
}
printf("\n");
}


int main()
{
int i=0;
struct node *pheader=NULL;
pheader=create_node(11);
for(i=0;i<7;i++)
{
//insert_head(pheader,create_node(i+2));
insert_tail(pheader,create_node(i+2));
}
display(pheader);
//insert_index(pheader,create_node(20),3);
reserve(pheader);
display(pheader);
//delate(pheader,5);
//display(pheader);
return 0;
}