leetcode 連結串列1
阿新 • • 發佈:2019-01-22
Given a singly linked list L: L 0→L 1→…→L n-1→L n,reorder it to: L 0→L n →L 1→L n-1→L 2→L 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; } }