单链表的逆置
下面是对带有头结点的空链表进行逆置的代码:
#include<time.h>
#include<math.h>
#include<ctype.h>
# include <stdio.h>
# include <stdlib.h>
#include<string.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;//数据域
struct Node *next;//指针域
}Node;
typedef struct Node* LinkList;
void createLinkList( LinkList *L,int n)//创建一个大小为n的单链表
{
LinkList s,p;
*L = (LinkList)malloc(sizeof(Node));//建立表头
p = *L;
for(int i = 1; i <= n;i++)
{
s = (LinkList)malloc(sizeof(Node));
s->data = i;
p->next = s;
p = s;
}
p ->next = NULL;
}
void inverseLinkList(LinkList *L)
{
LinkList s;
LinkList p;
LinkList q;
if((*L)->next ==NULL ||(*L)->next->next ==NULL);//当链表为空或者只有一个结点时,就不做任何处理
else
{
p = (*L)->next;//第一结点
q = p->next;
p->next = NULL;
s = p;
while(s != NULL )
{
s = q->next;//此结点需要保存的
q->next = p;
p = q;
q = s;
}
(*L)->next = p;
}
}
void main()
{
LinkList s,l;
int n =100;
createLinkList( &s,n);
l = s;
while(l->next != NULL )
{
printf("->%d",l->next->data);
l = l->next;
}
printf("\n");
inverseLinkList(&s);
while(s->next != NULL )
{
printf("->%d",s->next->data);
s = s->next;
}
return;
}