7、以下程序涉及单链表的建立、删除、添加、计算链表长度、排序和逆置:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}node;
/*建立单链表*/
node *creat()
{
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
node *head,*p,*s;
int x,cycle=1;
head = (node*)malloc(sizeof(node));
p = head;
printf("please input the data:\n");
while(cycle)
{
scanf("%d",&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 *head)
{
int n = 0;
node *p;
p = head;
while(p != NULL)
{
p = p->next;
n++;
}
printf("the length of chain is %d \n",n);
return n;
}
/* 打印链表*/
void print(node *head)
{
node *p;
p = head;
printf("the chain is :");
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
/* 删除节点*/
node *del(node *head, int num)
{
node *p = NULL,*q = NULL;
p = head;
while(num!=p->data && p->next!=NULL)
{
q = p;
p = p->next;
}
if(num == p->data)
{
if(num == head->data)
{
head = p->next;
free(p);
}
else
{
q->next = p->next;
free(p);
}
}
else
{
printf("the num could not been found !\n");
}
return head;
}
/* 添加节点*/
node *add(node *head, int num)
{
node *p1 = NULL,*p2 = NULL, *s = NULL;
p1 = head;
s = (node*)malloc(sizeof(node));
s->data = num;
while(s->data>p1->data && p1->next!=NULL)
{
p2 = p1;
p1 = p1->next;
}
if(s->data <= p1->data)
{
if(head == p1 )
{
s->next = p1;
head = s;
}
else
{
p2->next = s;
s->next = p1;
}
}
else
{
p1->next = s;
s->next = NULL;
}
print(head);
return head;
}
/* 链表排序*/
node *sort(node *head)
{
node *p = NULL;
p = head;
int n,temp,i,j;
n = length(p);
if(head == NULL || head->next == NULL)
{
return head;
}
for( j=0; j<n; j++)
{
p = head;
for( i=1; i<n-j; i++)
{
if(p->data > p->next->data)
{
temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
return head;
}
/* 单链表逆置*/
node *reverse(node *head)
{
node *p1,*p2,*p3;
if(head == NULL || head->next == NULL)
{
return head;
}
p1 = head;
p2 = p1->next;
while(p2->next !=NULL)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
p2->next = p1;
head->next = NULL;
head = p2;
print(head);
return head;
}
int main(void)
{
int m,n;
node * head = NULL;
head = creat();
print(head);
length(head);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("please input the del num :\n");
scanf("%d",&m);
del(head,m);
print(head);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("please input the add num :\n");
scanf("%d",&n);
add(head,n);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("the num after sort is :\n");
sort(head);
print(head);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("the num afer reverse is : \n");
reverse(head);
return 0;
}