首页 > 编程语言 > 详细

剑指offer反转链表(C++实现|测试用例)

时间:2020-10-28 21:10:02      阅读:53      评论:0      收藏:0      [点我收藏+]

代码:

#include<iostream>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* reverseList(ListNode* head) {

ListNode*cur = NULL;

ListNode*pre = head;

if(head == NULL||head->next==NULL)
{
return head;
}

while(pre!=NULL)
{
ListNode* p = pre->next;
pre->next = cur;
cur = pre;
pre = p;
}
return cur;
}
};

int main()
{
ListNode* head = new ListNode(1);
ListNode* sec = new ListNode(4);
ListNode* thr = new ListNode(5);
ListNode* fou = new ListNode(9);

head->next = sec;
sec->next = thr;
thr->next = fou;
fou->next = nullptr;

Solution s;
ListNode*p_head = s.reverseList(head);

while(p_head!=nullptr)
{
cout <<p_head->val<<endl;
p_head = p_head->next;
}
}

技术分享图片

 

剑指offer反转链表(C++实现|测试用例)

原文:https://www.cnblogs.com/shiheyuanfang/p/13893174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!