题目链接
https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
思路
非常经典的单向链表翻转。
思路就是固定原来的头结点init_head,把init_head后面的结点依次移动到链表首部,直到init_head后面没有结点,即init_head变成了链表尾部。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
if(head==nullptr)return v; // 边界特判
ListNode *init_head=head; // 最开始的头结点head,最终会变成尾结点
// 就地逆置链表,循环将每个init_head->next移动到首部,直到init_head->next为空
while(init_head->next!=nullptr){
ListNode* tmp=init_head->next; // tmp暂存要移动到首部的结点
init_head->next=tmp->next; // 将tmp从链表中去掉
tmp->next=head; // 将tmp放在头结点前面
head=tmp; // 更新头结点为tmp
}
// 遍历翻转后的链表,将其放入vector
ListNode* p=head;
while(p!=nullptr){
v.push_back(p->val);
p=p->next;
}
return v;
}
};
这篇博客主要介绍了如何解决LeetCode中的一个问题——从尾到头打印链表。通过固定头结点并逐步将后续节点逆置至链表头部,最终实现链表的反转。在代码实现中,使用了迭代的方式,逐步更新头结点,并在翻转后遍历链表将值存入vector返回。
1554

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



