面试题之反转单向链表

题目为:将一个单向链表反转,写出算法步骤或代码。
懵批了。今学习如下,
文章代码参考https://blog.csdn.net/K346K346/article/details/93371829,感谢!
单向链表反转示意图

#include<iostream>
using namespace std;

typedef struct linknode {
	int value;
	linknode * next;
} LinkNode;

/*循环遍历实现单向链表的反转*/
LinkNode * Reverse(LinkNode* head) {
	if (head == NULL || head->next == NULL) {
		return head;
	}

	LinkNode* pre = head, *cur = head->next;
	head->next = NULL;
	while (cur != NULL) {
		auto next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = next;
	}
	return pre;
}

void printLink(LinkNode* head) {
	while (head != NULL) {
		cout << head->value;
		head = head->next;
		if (head != NULL) {
			cout << "->";
		}
	}
	cout << endl;
}

/*递归实现单向链表反转*/
LinkNode* Reverse2(LinkNode* head) {
	//递归终止条件
	if (head == NULL || head->next == NULL) {
		return head;
	}
	LinkNode* newHead = Reverse2(head->next);
	head->next->next = head;
	head->next = NULL;
	return newHead;
}

int main(int argc, char* argv[]) {
	LinkNode* head = NULL, *cur = NULL;
	for (int i = 1; i <= 5; i++) {
		LinkNode* node = new LinkNode;
		node->value = i;
		node->next = NULL;

		if (head == NULL) {
			head = node;
			cur = head;
		} else {
			cur->next = node;
			cur = node;
		}
	}

	printLink(head);
	//反转单向链表
	auto newHead = Reverse(head);
	printLink(newHead);
}

其实总结起来就是
1.保存cur的next
2.修改cur的next指向pre
3.移动pre,cur指针:pre指向cur,cur指向前面保存的next
循环1,2,3直到cur为NULL结束,这时候pre就指向了反转后的head,完毕。
其实数据还是保存在原来的地方,只不过箭头指向倒过来了。

关于代码的编译和执行,感觉C++变化很大,结构体还可以使用new关键字,在Linux上面。

g++ -std=c++11 reverselink.cpp
./a.out
1->2->3->4->5
5->4->3->2->1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值