C语言实现单链表的逆置

项目场景:

用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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值