题目描述
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
样例
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL
题解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// 记录前驱结点
ListNode* pre = nullptr;
auto cur = head;
while(cur)
{
auto next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
- 包含IO:
// 迭代做法
// Iterative C++ program to reverse
// a linked list
#include <iostream>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
struct LinkedList {
Node* head;
LinkedList()
{
head = NULL;
}
/* Function to reverse the linked list */
void reverse()
{
// Initialize current, previous and
// next pointers
Node* current = head;
Node *prev = NULL, *next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
head = prev;
}
/* Function to print linked list */
void print()
{
struct Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
void push(int data)
{
Node* temp = new Node(data);
temp->next = head;
head = temp;
}
};
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
LinkedList ll;
ll.push(20);
ll.push(4);
ll.push(15);
ll.push(85);
cout << "Given linked list\n";
ll.print();
ll.reverse();
cout << "\nReversed Linked list \n";
ll.print();
return 0;
}
- 参考:GeeksforGeeks - Reverse a linked list
我爱你!!
这个图tql!!!!!!!酸q酸q感谢大佬,差点cpu烧坏了
哪有图啊
已经晕了/(ㄒoㄒ)/~~
题解那个图是动态的
之前网速不好 现在看见了 我还以为没图呢哈哈哈谢谢
没事没事
不多说·:我爱你
大佬无敌
tql
tql!
大佬图无敌
牛逼
大佬有心了
感谢大佬!!!!
这个图太棒啦
牛逼啊 ,看了y总几个视频差点绕进去了
牛哇牛哇
我不得不承认,这张图救了我,教会了我,非常感谢!!!
这个图绝了
666
这个图太好了
这个图生动明确
嗯🤣