链表是个好东西,分享出来记录在这里,方便查找。
另外如struct member * list新建节点要赋值的时候,必须先分配内存空间list = (struct member *)malloc(sizeof(struct member))
然后才能赋值list->data = xxxx;
/*20131215 Denyz 链表是输入输出及就地逆转*/
#include <stdio.h>
#include <malloc.h>
typedef struct{
int num;
int name;
}Elementype;
typedef struct LinkList{
Elementype elem;
struct LinkList *next;
}LList;
/*链表的创建i个元素,返回Head指针*/
LList *CreatList(int length)
{
int i=0,data;
LList *Head,*PL,*PLn;
printf("Input the Link List:\n");
Head = (LList *)malloc(sizeof(LList));
PL=Head->next=(LList *)malloc(sizeof(LList));//第一个结点
scanf("%d",&PL->elem.num);
PL->next=NULL;
for(i=1;i<length;i++)
{
PLn=(LList *)malloc(sizeof(LList));//
scanf("%d",&data);
PLn->elem.num=data;
PLn->next=PL->next;
PL->next=PLn;//将新结点接入链表
PL=PLn;
}
return Head;
}
//线性链表就地逆转函数,用“砍头”法
//砍断头结点后,在头结点和Head指针的中间不断插入链表的结点,从而达到链表逆转的目的
void Reverse(LList *Head)
{
LList *PL1,*PLn,*Tmp;
PL1=Head->next;
PLn=PL1->next;//先保存头结点后面一个结点的指针,不然头结点砍断后将丢失后面的结点
PL1->next=NULL;//砍断第一个结点,也就是头结点
while(PLn)
{
Tmp=PLn->next;//用Tmp保存当前结点的next结点的指针,确保砍断当前结点后丢失后面的结点。
PLn->next=PL1;
Head->next=PLn;
PL1=PLn;//PLn成为下一个结点的next指针的指向目标
PLn=Tmp;//PLn变成需要插入的结点的指针了
}
}
void ShowList(LList *Head)
{
LList *PL;
PL=Head->next;
printf("List is: ");
while(PL)
{
printf("%d ",PL->elem.num);
PL=PL->next;
}
printf("\n");
}
void main()
{
int num;
LList *Head;
Head=CreatList(4);/*构建4个数据的链表*/
ShowList(Head);
printf("Reverse the LinkList:\n");
Reverse(Head);
ShowList(Head);
getch();
}