1. 程式人生 > >leetcode 連結串列1

leetcode 連結串列1

Given a singly linked list LL 0L 1→…→L n-1L n,reorder it to: L 0L n L 1L n-1L 2L n-2→…

You must do this in-place without altering the nodes' values.

For example,Given{1,2,3,4}, reorder it to{1,4,2,3}.

思路:先從中間切斷分為兩個連結串列,將後一個連結串列反轉,再逐個插入到前一個連結串列。

#include<iostream>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}

};
//連結串列結構定義

ListNode* reverse(ListNode *head){
		ListNode* pRH = NULL;
		ListNode* p = head;
		ListNode* pre = NULL;
		// 保持在處理每個節點時候一樣,初始化NULL 第一個節點重新指向NULL

		while (p != NULL){
			ListNode *tmp = p->next;
			if (tmp == NULL) pRH = p;
			p->next = pre;
			pre = p;
			p = tmp;
		}
		return pRH;
	}
// 反轉連結串列
void reorderList(ListNode *head) {

		int length = 0;
		ListNode *p = head;
		// 統計列表的總長度
		while (p != NULL){
			length++;
			p = p->next;
		}

		int tmp = 0;
		ListNode *q = head;

		while (tmp < ((length - 1) / 2)){
			q = q->next;
			tmp++;
		}

		ListNode *head1 = q->next;
		q->next = NULL;

		ListNode *head2 = reverse(head1);

		p = head;
		q = head2;
                // 連結串列從中間切斷分為兩個部分
		while(p != NULL && q != NULL){
			ListNode *tp = q->next;
			q->next = p->next;
			p->next = q;
			if (q)
				p = q->next;
			q = tp;
		}
// 將連結串列的後半部分反轉後,連結到前半部分的連結串列
	}

int main(){  //測試
	int a[] = {1, 2, 3, 4, 5,6,7,8};
	ListNode *head = new ListNode(a[0]);
	ListNode *p = head;

	for (int i = 1; i < 8; i++){
		p->next = new ListNode(a[i]);
		p = p->next;
	}

	reorderList(head);
	ListNode *q = head;
	while (q){
		cout << q->val << endl;
		q = q->next;
	
	}

}