反转链表牛客

题目链接

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=295&tqId=23286&ru=/exam/intelligent&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fintelligent

 给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。 数据范围: 要求:空间复杂度 ,时间复杂度 。 如当输入链表{1,2,3}

#include<iostream>
using namespace std;
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(nullptr) {
	}
};
class Solution {
public:
	ListNode* ReverseList(ListNode* pHead) {
		if (pHead == nullptr)
		{
			return pHead;
		}
		else
		{
			ListNode* pre = nullptr;//前一个结点(1的next指针为空)
			ListNode* cur = pHead;//当前结点(1)
			ListNode* ne = nullptr;//当前结点的下一结点(2)
			while (cur != nullptr)
			{
				ne = cur->next;//保存好2的下一节点3后
				cur->next = pre;//将结点2的指针指向反转,使其指向指向1结点
				pre = cur;
				cur = ne;
			}
			return pre;
		}
	}
};
int main()
{
	ListNode node1(1), node2(2), node3(3);
	node1.next = &node2;
	node2.next = &node3;
	cout << node1.val << " " << node1.next<<" " << &node2 << endl;
	Solution sol;
	ListNode* head=sol.ReverseList(&node1);
	cout << head->val << endl;
	while (head!=nullptr)
	{
		cout << head->val << " ";
		head = head->next;
	}
	cout << endl;
	//测试空结点
	cout << "空结点测试~~~~~~~~~~~" << endl;
	ListNode* node4 = nullptr;
	Solution so2;
	ListNode* head2 = so2.ReverseList(node4);
	while (head2 != nullptr)
	{
		cout << head2->val << " ";
		head2 = head->next;
	}
	cout << endl;
	//测试一个结点
	cout << "一个结点测试~~~~~~~~~~~" << endl;
	ListNode node5(7);
	Solution so3;
	ListNode* head3= so3.ReverseList(&node5);
	while (head3 != nullptr)
	{
		cout << head3->val << " ";
		head3 = head3->next;
	}
	cout << endl;
	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值