描述
将给定的单链表\ L L: L_0→L_1→…→L_{n-1}→L_ nL0→L1→…→Ln−1→Ln
重新排序为:L_0→L_n →L_1→L_{n-1}→L_2→L_{n-2}→…L0→Ln→L1→Ln−1→L2→Ln−2→…
要求使用原地算法,不能只改变节点内部的值,需要对实际的节点进行交换。
示例1
输入:
{1,2,3,4}
复制返回值:
{1,4,2,3}
复制说明:
给定head链表1->2->3->4, 重新排列为 1->4->2->3,会取head链表里面的值打印输出
示例2
输入:
{1,2,3,4,5}
复制返回值:
{1,5,2,4,3}
复制说明:
给定head链表1->2->3->4->5, 重新排列为 1->5>2->4->3,会取head链表里面的值打印输出
示例3
输入:
{}
复制返回值:
{}
复制
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if (!head || !head->next) {
return;
}
ListNode *slow = head, *fast = head;
ListNode *preSlow = NULL;
while (fast && fast->next) {
preSlow = slow;
slow = slow->next;
fast = fast->next->next;
}
preSlow->next = NULL;
ListNode *pre = slow,*cur = slow->next;
pre->next = NULL;
while (cur) {
ListNode *last = cur->next;
cur->next = pre;
pre = cur;
cur = last;
}
ListNode *first = head, *second = pre, *temp1 = NULL, *temp2 = NULL;
while (first && second) {
temp1 = first->next;
temp2 = second->next;
first->next = second;
if (temp1) {
second->next = temp1;
}
first = temp1;
second = temp2;
}
}
};
链表常用的快慢指针找中间值
学习了C++版本的翻转链表,使用三个变量,pre,cur,last
last = cur->next;
cur->next = pre;
pre = cur;
cur = last;
还有C++版本的链表合并,这个比较简单