86. 分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
解题
(1)新建表头节点dummyhead;
(2)遇到比x小的加入节点,遇到比x大的放在原位,跳过比x小的,最后合并即可;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode dummyhead;
ListNode *p=&dummyhead;
while(head&&head->val<x){
p->next=head;
head=head->next;
p=p->next;
}
ListNode *front= head;
ListNode *rear= head;
while(rear){
rear=rear->next;
while(rear&&rear->val>=x) {
front=front->next;
rear=rear->next;
}
if(rear){
p->next=rear;
p=p->next;
front->next=rear->next;
}
}
p->next=head;
return dummyhead.next;
}
};
建立两个链表,一个存储比x小的,一个存储比x大的,合并即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode small;
ListNode * s= &small;
ListNode big;
ListNode * b=&big;
while(head){
if(head->val<x){
s->next=head;
s=s->next;
}
else {
b->next=head;
b=b->next;
}
head=head->next;
}
b->next=nullptr;
s->next=big.next;
return small.next;
}
};
注意点
出循环后需将b->next赋为空指针,不然会变为指针环;
92. 反转链表 II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
解题
注意要建立新表头,防止测试点要求整个反转链表;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode dummyhead;
dummyhead.next=head;
ListNode *first;
ListNode * second;
ListNode * tmp;
first=head;
ListNode *start=&dummyhead;
for(int i=1;i<m;i++){
start=start->next;
first=first->next;
}
second=first->next;
for(int i=m;i<n;i++){
tmp=second->next;
second->next=first;
first=second;
second=tmp;
}
tmp=start->next;
start->next=first;
tmp->next=second;
return dummyhead.next;
}
};

本文详细解析了链表的分隔与反转算法,通过实例展示了如何高效地对链表进行分区及部分反转,适合初学者及进阶者深入理解链表操作技巧。

被折叠的 条评论
为什么被折叠?



