反转单链表

本文介绍了一种链表反转的方法,并提供了完整的C++实现代码。通过维护三个指针:当前节点、前一个节点和下一个节点,该算法能有效地完成链表的反转操作。文章最后展示了一个包含0到9十个元素的链表反转示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    始终维护三个链表节点,即当前节点,前一个节点与下一个节点。

#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

struct Node{
	int key;
	Node* next;

	Node(int k) : key(k), next(nullptr){}
};

Node* makeList(const vector<int>& vec){
	Node* head = nullptr;
	Node* node = nullptr;

	for(size_t i = 0; i < vec.size(); ++i){
		if(i == 0){
			node = new Node(vec[i]);
			head = node;
		}else{
			node->next = new Node(vec[i]);
			node = node->next;
		}
	}

	return head;
}

Node* invert(Node* head){
	if(head == nullptr || head->next == nullptr) return head;

	Node* pre = head;
	Node* cur = head->next;
	Node* nxt = nullptr;
	pre->next = nullptr;

	while(cur){
		nxt = cur->next;
		cur->next = pre;
		pre = cur;
		cur = nxt;
	}

	return pre;
}

int main(){
	int arr[] = {0,1,2,3,4,5,6,7,8,9};
	vector<int> vec(arr, arr + sizeof(arr)/sizeof(int));

	Node* head = makeList(vec);
	Node* h = invert(head);
	while(h){
		cout << h->key << " ";
		h = h->next;
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值