//翻转一个链表
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//创建一个含有n个元素的单链表
LNode *createList(int n){
LNode *head = NULL,*p1,*p2;
for(int i=1;i<=n;i++)
{
p1 = (LinkList)malloc(sizeof(LNode));
if(p1==NULL)
return NULL;
printf("输入链表中第%d个数",i);
scanf("%d",&p1->data);
if(head==NULL)
{
head = p1;
p2 = p1;
}else
{
p2->next = p1;
p2 = p1;
}
}
p2->next = NULL;
return head;
}
//打印链表
void printList(LNode *head){
LNode *p = head;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
}
//使用三个指针依次改变节点指向翻转链表
LinkList reverseList(LinkList head)
{
LinkList pNode = head; //当前要翻转的节
LinkList pPre = NULL; //翻转后当前节点前一个节点
LinkList pNext = NULL; //保存翻转前当前节点后一个节点
LinkList resHead = NULL; //翻转后链表头节点
while(pNode != NULL)
{
pNext = pNode->next;
if(pNext==NULL)
{
resHead = pNode;
}
pNode->next = pPre;
pPre = pNode;
pNode = pNext;
}
return resHead;
}
int main(int argc, char *argv[]) {
//创建顺序链表
LNode *head1 = createList(5);
printList(head1);
printf("\n");
printList(reverseList(head1));
printf("\n");
return 0;
}
翻转链表
最新推荐文章于 2025-07-30 10:44:16 发布
1204

被折叠的 条评论
为什么被折叠?



