日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Leedcode8-reorder-list

發布時間:2025/3/15 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leedcode8-reorder-list 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include<iostream> #include<vector> using namespace std; //Definition for singly-linked list. /*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→…*/ struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {} };//class Solution { //沒有考慮將最后一個結點刪除,并把第二個結點的指針域置為空 //public: //思路錯誤 // void reorderList(ListNode *head) { // if (head == NULL || head->next==NULL) // return; // ListNode *pEnd = head->next; // while (pEnd) { // pEnd = pEnd->next; // } // pEnd->next = head->next; // head->next = pEnd; // } //}; class Solution { public:void reorderList(ListNode *head) {ListNode* p = head; //保留頭結點ListNode *rear = head; while(p!=NULL && p->next!=NULL){ while (rear->next->next!=NULL) { //找到倒數第二個結點rear = rear->next;}ListNode *temp = rear->next; //保留最后一個結點rear->next = NULL; //將倒數第二個結點的指針域置為空//插入temp(最后一個結點)將temp插入到p(頭結點)和p->next之間temp->next = p->next;p->next = temp; //將結點插入rear = temp->next; //保留結點為插入結點的后一個結點p = temp->next; //將頭結點保留為插入結點的后一個結點}} };//大神思路 class Solution { public:void reorderList(ListNode *head) {if (!head) return;vector<int> V;ListNode* ptr = head;/*for(; ptr!=NULL; ptr=ptr->next){V.push_back(ptr->val);}*/while (ptr != NULL) {V.push_back(ptr->val);ptr = ptr->next;}int i = 0;int j = V.size() - 1;int flag = 0;ptr = head;while (i <= j) {if ((flag % 2) == 0) {ptr->val = V[i]; i += 1;}else {ptr->val = V[j]; j -= 1;}++flag;ptr = ptr->next;}} };

?

總結

以上是生活随笔為你收集整理的Leedcode8-reorder-list的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。