/*
从表尾到到表头逆向创建链表,反转链表
逆向创建链表:新节点插入到头结点
反转链表:需要三个指针
*/
# include <stdio.h>
# include <malloc.h>
//节点类型
typedef struct node
{
int data;
struct node * pNext;
}NODE, * PNODE;
PNODE converse_creat_list();
void traverse(PNODE pHead);
PNODE converse(PNODE pHead);
int main(void)
{
PNODE pHead = converse_creat_list(); //创建链表
printf("建立链表:");
traverse(pHead);
//反转链表
printf("反转链表:");
PNODE pCon = converse(pHead);
traverse(pCon);
return 0;
}
//创建链表
PNODE converse_creat_list()
{
int i;
int len, val;
printf("输入创建链表的长度:");
scanf("%d", &len);
PNODE pHead = (PNODE)malloc(sizeof(NODE)); //创建头结点
pHead->pNext = NULL;
PNODE pNew;
for(i = 0; i < len; i++)
{
printf("输入插入的第%d个元素 val:", len - i);
scanf("%d", &val);
pNew = (PNODE)malloc(sizeof(NODE)); //新节点
pNew->data = val;
pNew->pNext = pHead->pNext; //新节点插在头结点
pHead->pNext = pNew;
}
return pHead;
}
//反转链表
PNODE converse(PNODE pHead)
{
PNODE p = pHead->pNext;
PNODE pCon = (PNODE)malloc(sizeof(NODE)); //新链表的头结点
pCon->pNext = NULL;
PNODE pMid = NULL;
PNODE pTail;
while(p)
{
pTail = pMid;
pMid = p;
p = p->pNext;
pMid->pNext = pTail;
}
pCon->pNext = pMid;
return pCon;
}
//遍历链表
void traverse(PNODE pHead)
{
PNODE p = pHead->pNext; //指向首节点
while(p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
C语言:从表尾到到表头逆向创建链表,反转链表
最新推荐文章于 2022-08-31 22:35:51 发布