1. 翻转链表
题目链接
常用两种思路,第一种是启发式,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* next;
pre -> next = nullptr;
while(cur != nullptr) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
第2种方法是递归,
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode* ans = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return ans;
}
2. K 个一组翻转链表
K 个一组翻转链表 题目链接
基本思路:用计数+栈实现分段,K个一组地翻转链表。
#include <bits/stdc++.h>
#include <stack>
using namespace std;
struct list_node {
int val;
struct list_node *next;
};
list_node *input_list() {
int val, n;
scanf("%d", &n);
list_node *phead = new list_node();
list_node *cur_pnode = phe