1. 程式人生 > 實用技巧 >Debain-10.4 安裝 oracle 12.2.0.1 資料庫database軟體

Debain-10.4 安裝 oracle 12.2.0.1 資料庫database軟體

143. 重排連結串列

難度中等260給定一個單鏈表 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() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    
void reorderList(ListNode* head) { ListNode *middle, *tail, *right, *left, *t1, *t2; if(head && head->next) { middle = Find_middle(head); tail = middle->next; middle->next = NULL; right = Reorder(tail); left = head; while
(left&&right) { t1 = left->next;//t1 = 2 t1 = 3 t2 = right->next;//t2 = 4 t2 = null left->next = right;//1->5 2->4 left = t1;//left = 2 left = 3 right->next = left;//5->2 4->3 right = t2;//right = 4 right = null } } } ListNode *Find_middle(ListNode *head) { ListNode *fast, *slow; fast = head->next; slow = head; while(fast&&fast->next) { fast = fast->next->next; slow = slow->next; } return slow; } ListNode *Reorder(ListNode *head) { //1->2->3->4->5 ListNode *current, *pre, *temp; if(head == NULL||head->next==NULL) return head; current = head;//current = 1 pre = current->next;//pre = 2 current->next = NULL;//1->null while(pre) { temp = pre->next; //temp = 4 temp = 5 temp = null pre->next = current;// 3->2 4->3 5->4 current = pre;//current = 3 current = 4 current = 5 pre = temp;//pre = 4 pre = 5 pre = null } return current; } };