链表逆序

本文介绍了一个简单的链表创建及遍历方法,并实现了两种不同的链表逆序算法:迭代和递归。通过实例演示了如何创建链表、打印链表元素及进行链表逆序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>


typedef struct Node
{
int data;
struct Node *pNext;


}NODE, *PNODE;


//创建链表
PNODE create_List(void)
{
int len;
int val;
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("exit\n"); 
exit(1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入您要生成的结点个数:");
scanf("%d",&len);
for(int i = 0; i < len; i++)
{
printf("请输入您要生成的第%d个结点的值:",i + 1);
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("exit\n");
exit(1);
}
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}


//遍历输出
void traverse_List(PNODE _pNode)
{
PNODE p = _pNode->pNext;
while (NULL != p)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}


void traverse_List2(PNODE _pNode)
{
PNODE p = _pNode;
while (NULL != p->pNext)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}


//逆序链表
PNODE reverse_List(PNODE _pNode)
{
PNODE p1,p2,p3;
if (_pNode->pNext == NULL || _pNode == NULL)
{
return _pNode;
}
p1 = _pNode->pNext;
p2 = p1->pNext;
p1->pNext = NULL;
while(p2)
{
p3 = p2->pNext;
p2->pNext = p1;
p1 = p2;
p2 = p3;
}
_pNode->pNext = p1;
return _pNode;
}


//递归逆序
PNODE reverse_List2(PNODE _pNode)
{
if (_pNode == NULL || _pNode->pNext == NULL)
{
return _pNode;
}
PNODE pNew = reverse_List2(_pNode->pNext);
_pNode->pNext->pNext = _pNode;
_pNode->pNext = NULL;
return pNew;
}


int _tmain(int argc, _TCHAR* argv[])
{
PNODE pHead = NULL;
pHead = create_List();
traverse_List(pHead);
pHead = reverse_List(pHead);
traverse_List(pHead);
pHead = reverse_List2(pHead);
traverse_List2(pHead);
_getch();
return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值