部分图片参考小象学院
剑指 Offer 24. 反转链表
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
https://leetcode-cn.com/problems/reverse-linked-list/
题目:
已知链表头节点指针head,将链表逆序。(不可申请额外的空间)
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
思路:
依次遍历链表节点,没遍历一个节点就逆置一个节点。
具体做法:
#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* new_head = NULL; //创建新头指针
while (head)
{
ListNode* temp = head->next; //1.备份head->next
head->next = new_head; //2.将head->next指向new_head
new_head = head; //3.1 移动new_head
head = temp; //3.2 移动head
}
return new_head;
/********** 填写结束 *********/
}
};
void showList(ListNode* head) //遍历
{
while (head)
{
cout << head->val << endl;
head = head->next;
}
}
void test01()
{
ListNode a(1); //创建数据用于测试
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = NULL;
ListNode* head = &a; //头指针
cout << "Before reverse: " << endl;
showList(head); //遍历
cout << "After reverse: " << endl;
Solution s;
head = s.reverseList(&a); //传入参数进行逆序
showList(head); //遍历
}
int main()
{
test01();
system("pause");
return 0;
}