项目场景:
用C语言实现单链表的逆置
问题描述
首先输入建立的链表长度,然后输入链表,系统打印链表逆置之前的内容与逆置之后的内容
控制台内容如下:
请输入您要建立的链表长度:
5
请输入您要输入的数据:
1 2 3 4 5
before:
1 2 3 4 5
after:
5 4 3 2 1
–
完整代码:
新手联系中,如有不足请指点。:
借鉴大佬博客(https://blog.csdn.net/odaynot/article/details/7992771)
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
//创建链表 尾插法
Node *CreatList(void) {
int value, n;
Node *phead, *p, *q;
phead = (Node *)malloc(sizeof(Node));
q = phead; //q为表尾指针
printf("请输入您要建立的链表长度:\n");
scanf("%d", &n);
printf("请输入您要输入的数据:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &value);
p = (Node *)malloc(sizeof(Node));
p->data = value;
q->next = p;
q = p;
}
q->next = NULL;//表尾指针值为空
return phead;
}
//链表的逆置
Node *ReverseList(Node *phead) {
Node *p, *q, *r; //p为工作指针,q为p的后继,以防断链
p = phead->next;
phead->next = NULL;
while (p != NULL) { //头节点不空
q = p->next;
p->next = phead->next;
phead->next = p;
p = q;
}
return phead;
}
//输出链表
void ShowList(Node *phead) {
Node *p;
p = phead->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *phead;
phead = CreatList();
printf("before:\n");
ShowList(phead);
phead = ReverseList(phead);
printf("after:\n");
ShowList(phead);
return 0;
}