143. 重排链表

https://leetcode-cn.com/problems/reorder-list/description/

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode* Reverse(ListNode* head) {
		ListNode* prev = NULL;
		ListNode* next;
		while (head) {
			next = head->next;
			head->next = prev;
			prev = head;
			head = next;
		}
		return prev;
	}

	void reorderList(ListNode* head) {
		if (!head || !head->next || !head->next->next) {
			return;
		}

		ListNode* Head = new ListNode(-1);
		ListNode* tail = Head;
		Head->next = head;
		ListNode* cur = Head;
		ListNode* next = Head;

		while (next && next->next) {
			cur = cur->next;
			next = next->next->next;
		}

		next = cur->next;
		next = Reverse(next);
		cur->next = NULL;
		cur = head;
		while (next && cur) {
			tail->next = cur;
			tail = tail->next;
			cur = cur->next;


			tail->next = next;
			tail = tail->next;
			next = next->next;
		}
		if (next) {
			tail->next = next;
		}
		if (cur) {
			tail->next = cur;
		}
		head = Head->next;
	}
};

143. 重排链表_第1张图片

你可能感兴趣的:(LeetCode,链表)