使用带头结点的方式进行创建,使用一个临时链表来实现对链表的逆转
链表的定义
typedef struct List
{
int data;
struct List * next;
}List , *LinkList;
带头结点链表的初始化
LinkList createList()
{
LinkList linklist = (LinkList) malloc(sizeof(List));
if(linklist == NULL)
{
printf("create fail\n");
}
linklist->next = NULL;
return linklist;
}
带链表增加节点
void InsertList(LinkList linklist ,LinkList add_data)
{
add_data->next = linklist->next;
linklist->next = add_data;
printf("insert data is %d \n ",linklist->next->data);
}
逆转函数
void reverse(LinkList linklist)
{
LinkList p,tmp;
tmp = (LinkList)malloc(sizeof(List));
tmp->next = linklist->next;
linklist->next = NULL;
while(tmp->next != NULL)
{
p = (LinkList)malloc(sizeof(List));
p->data = tmp->next->data;
p->next = linklist->next;
linklist->next = p;
tmp= tmp->next;
}
}
打印链表
void printList(LinkList linklist)
{
while(linklist->next != NULL)
{
printf("%d ",linklist->next->data);
linklist=linklist->next;
}
}
完整的程序
#include<stdio.h>
#include<stdlib.h>
typedef struct List
{
int data;
struct List * next;
}List , *LinkList;
LinkList createList()
{
LinkList linklist = (LinkList) malloc(sizeof(List));
if(linklist == NULL)
{
printf("create fail\n");
}
linklist->next = NULL;
return linklist;
}
void printList(LinkList linklist)
{
while(linklist->next != NULL)
{
printf("%d ",linklist->next->data);
linklist=linklist->next;
}
}
void InsertList(LinkList linklist ,LinkList add_data)
{
add_data->next = linklist->next;
linklist->next = add_data;
printf("insert data is %d \n ",linklist->next->data);
}
void reverse(LinkList linklist)
{
LinkList p,tmp;
tmp = (LinkList)malloc(sizeof(List));
tmp->next = linklist->next;
linklist->next = NULL;
while(tmp->next != NULL)
{
p = (LinkList)malloc(sizeof(List));
p->data = tmp->next->data;
p->next = linklist->next;
linklist->next = p;
tmp= tmp->next;
}
}
int main()
{
int i ;
LinkList list = createList();
for( i = 0; i < 10 ; i++)
{
LinkList p = (LinkList)malloc(sizeof(List));
p->data = i ;
p->next = NULL;
InsertList(list,p);
}
printf("list is: \n");
printList(list);
reverse(list);
printf("\nreverse list is :\n");
printList(list);
return 0;
}
运行结果:
|