单链表逆转(自己根据题干实现)
程序员文章站
2022-04-24 14:09:25
...
题目:
PTA成功代码:
List Reverse( List L )
{
List x, y;
x = L;
L = NULL;
while (x)
{
y = x;
x = x->Next;
y->Next = L;
L = y;
}
return L;
}
本地代码(实现了输入逆转输出释放):
//https://pintia.cn/problem-sets/15/problems/724
//链表倒转
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
// 定义一个结构体
typedef struct student
{
int ID;
struct student *next;
} LinkList;
// 创建首尾节点和普通节点
LinkList *head = NULL, *node = NULL, *end = NULL;
// 创建一个链表,链表节点个数为n
LinkList *create( int n )
{
for (int i = 0; i < n; i++)
{
node = ( LinkList* )malloc( sizeof( LinkList ) );
memset(node,0,sizeof(node));
printf("请输入第%d个人的ID\n", i+1);
scanf("%d",&node->ID);
if (i == 0)
{
head = node;
end = head;
}
end->next = node;
end = node;
}
end->next = NULL;
return head;
}
// 循环遍历然后打印
void put( LinkList *head, int n )
{
LinkList *t = head;
while (1)
{
printf("%d\n", t->ID );
t = t->next;
if ( t->next == NULL )
{
printf("%d\n", t->ID );
break;
}
}
}
// 把链表倒叙
LinkList *reverse( LinkList *head )
{
LinkList *x, *y;
x = head;
head = NULL;
while ( x != NULL )
{
y = x;
x = x->next;
y->next = head;
head = y;
}
return head;
}
// 释放内存
void freeLinkList( LinkList *head )
{
LinkList *freeNode = NULL;
while ( head != NULL)
{
freeNode = head;
head = head->next;
free( freeNode );
}
}
int main()
{
int n;
scanf("%d", &n);
LinkList *head;
head = create(n);
put( head, n );
puts("After reverse:");
head = reverse( head );
put( head, n );
freeLinkList( head );
return 0;
}
单链表逆转思路:
推荐阅读