1、描述
反转一个单向链表
题目链接
2、关键字
反转
3、思路
3步迭代
递归
栈
4、notes
3步迭代
1、保存后方 tem=cur->next
2、反指前方 cur->next=pre
3、迭代前进 pre=cur; cur=tem;
5、复杂度
时间:O(N)
空间:O(1)
6、code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 初始化
Node* ini(vector<int>& nums, int n) {
Node* dummy = new Node(0);
Node* head = dummy;
for(int i = 0; i < n; i++) {
Node* newNode = new Node(nums[i]);
newNode->next = head->next;
head->next = newNode;
}
delete dummy;
return head->next;
}
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head; // 特判0,1
ListNode * pre=nullptr; // 初始化
auto cur=head;
auto tem=head;
//while(!cur){ ******************************* 又是这里 !!!!!!!
while(cur){
tem=cur->next; //保存后方
cur->next=pre; // 反指前方
pre=cur; // 迭代前进
cur=tem;
}
return pre;
}
};
三、翻转其中的一部分
给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
题解
/**
* 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* reverseBetween(ListNode* head, int left, int right) {
if(left==right) return head;
ListNode* dummy_head=new ListNode(0,head); // 构造函数,使->next=head
ListNode* t1=dummy_head;
int ind=0;
while(ind < left-1){
t1 = t1->next;
ind++;
}
ListNode* l_left=t1; // 翻转左边的最后元素,
t1 = t1->next;
ind++;
ListNode* cur = t1; // 翻转的第一个元素
ListNode* pre = nullptr; // 从翻转第一个元素开始,设置pre节点
ListNode* t2=cur; // 记录第一个节点,等最后好用
while(left <= right){
ListNode* next = cur->next; // 1、暂存后一个节点
cur-> next = pre; // 2、后指向前一个
pre = cur; // 3、前进
cur = next; // 3、同步前进
left ++;
}
l_left->next = pre;
t2->next = cur;
return dummy_head->next;
}
};