算法之反转链表

问题很简单:反转一个链表。

其实就是对链表的基础操作,思路是顺着链表头结点的next指针遍历整个链表。假设链表前三个节点分别为A、B、C。

1.A->next = C;

2.B->next = A;

以A的next节点作为判断依据即可遍历整个链表并实现前后两个节点的指针反转。虽然思路很简单,但写的时候发现C的快忘得差不多了,为了复习C我在C++工程中完全以C的代码实现的。诸如new方法我用malloc方法替换手动为结构体分配堆内存等。并不影响程序运行,代码如下:

#include<iostream>
using namespace std;

typedef struct Node {
	int data;
	struct Node * next;
}Node;

//生成一个节点
struct Node* CreateNode(){
	struct Node * node = (struct Node*)malloc(sizeof(struct Node));
	node->next = NULL;
	return node;
}

//构建一个链表
void CreateNodeTable(struct Node * start){
	start->data = 0;
	struct Node * preNode = start;
	struct Node * thisNode;
	for (int i = 1; i < 10; i++) {
		thisNode = CreateNode();
		thisNode->data = i;
		preNode->next = thisNode;
		preNode = thisNode;
	}
}

//打印一个链表
void PrintNodeTable(struct Node * start) {
	struct Node * temp = start;
	while (temp -> next != NULL)
	{
		cout << temp->data;
		temp = temp->next;
	}
	cout << temp->data;
	cout << endl;
}

//翻转一个链表
struct Node * ReverseNodeTable(struct Node * start) {
	struct Node * preNode = start;
	struct Node * thisNode = start;
	while (start -> next != NULL)
	{
		thisNode = start->next;
		start->next = start->next->next;
		thisNode->next = preNode;
		preNode = thisNode;
	}
	return thisNode;
}

int main() {
	struct Node * start = CreateNode();
	CreateNodeTable(start);
	PrintNodeTable(start);
	struct Node * newStart = ReverseNodeTable(start);
	PrintNodeTable(newStart);
	//防止秒退死循环
	while (1)
	{

	}
}

显然时间复杂度仅为O(n),空间复杂度是常数级的复杂度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值