单链表(原地)逆置

单链表实现逆置

从头遍历链表,使每一个结点都指向该结点的上一个节点。最后再处理头结点与为结点即可。

三个指针

对于一个单链表来说,我们不可能从一个结点(Node *)找到它的上一个节点,所以我们需要额外定义一个指针(Node *)指向该结点的上一个结点。此外在改变当前结点next指针的指向时会断开与下一结点的连接,所以我们还需要一个指针(Node *)指向当前结点的下一个结点。

如图所示:

指向当前结点,改变当前结点next 指向,同时自动与其后续结点断开;

s 初始为空,代表尾结点指向NULL,随着i 的移动,指向新链表的头;

指向 i 的下一个结点,以便在单链表断开的情况下还能继续遍历链表。

代码如下:

//单链表逆置 
void Reverse(LNode* List)
{
	LNode* s = nullptr;//空指针	//开始时为空指针,循环时成为新链表的头(类似头插)
	LNode* i = nullptr;			//遍历链表,改变指针(next)指向
	LNode* t = List->next;		//保留断开处的链表
	
	while (t != nullptr)
	{
		i = t;
		t = t->next;	//保存断开处的地址

		i->next = s;	//改变当前结点指向
		s = i;
	}
	List->next = s;    //头结点
}

 

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用迭代或递归的方式来实现单链表原地逆置。下面是使用迭代方式的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct Node { int data; struct Node* next; }; // 原地逆置单链表 struct Node* reverseList(struct Node* head) { struct Node *prev = NULL; struct Node *curr = head; struct Node *next = NULL; while (curr != NULL) { next = curr->next; // 保存当前节点的下一个节点 curr->next = prev; // 当前节点指向前一个节点 prev = curr; // 更新前一个节点为当前节点 curr = next; // 更新当前节点为下一个节点 } return prev; // 返回逆置后的头节点 } // 打印链表 void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } int main() { // 创建链表 struct Node* head = (struct Node*)malloc(sizeof(struct Node)); struct Node* second = (struct Node*)malloc(sizeof(struct Node)); struct Node* third = (struct Node*)malloc(sizeof(struct Node)); struct Node* fourth = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = fourth; fourth->data = 4; fourth->next = NULL; printf("原链表:"); printList(head); // 逆置链表 head = reverseList(head); printf("逆置后的链表:"); printList(head); return 0; } ``` 这段代码首先定义了一个单链表节点结构体 `Node`,包含一个整型数据 `data` 和指向下一个节点的指针 `next`。然后,定义了 `reverseList` 函数,通过迭代的方式实现了单链表原地逆置。最后,在 `main` 函数中创建了一个简单的链表,并调用 `reverseList` 函数进行逆置,打印出逆置后的结果。 希望能帮到你!如果有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫RT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值