【Leetcode】Reorder List
来源:互联网 发布:快乐识字软件 编辑:程序博客网 时间:2024/06/10 16:41
遇到问题:判断fast->next->next是否为空,需要先判断fast->next是否为空。
题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}
.
//// main.cpp// ReorderList//// Created by stongan on 4/29/15.// Copyright (c) 2015 pang stongan. All rights reserved.//#include <iostream>using namespace std;//Definition for singly-linked list.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* fast = head; ListNode* slow = head; // while(fast != NULL){// cout <<"fast:" <<fast->val <<endl;// fast = fast->next;// }// while(slow != NULL){// cout <<"slow:" <<slow->val <<endl;// slow = slow->next;// } //与判断fast->next->next是否为空,需要先判断fast->next是否为空 while(fast->next != NULL && fast->next->next != NULL){ fast = fast->next->next; slow = slow->next; } fast = slow; slow = slow->next; fast->next = NULL; ListNode* pre = slow; slow = slow->next; pre->next = NULL; while(slow != NULL){ ListNode* next = slow->next; slow->next = pre; pre = slow; slow = next; } ListNode* cur = head; while(cur != NULL && pre!=NULL){ ListNode* next1 = cur->next; ListNode* next2 = pre->next; cur->next = pre; pre->next = next1; cur = next1; pre = next2; } }};int main(int argc, const char * argv[]) { Solution sol; ListNode* tmp = new ListNode(1); ListNode* tmp2 = new ListNode(2); ListNode* tmp3 = new ListNode(3); //ListNode* tmp4 = new ListNode(4); tmp->next = tmp2; tmp2->next = tmp3; //tmp3->next = tmp4; sol.reorderList(tmp); while(tmp!=NULL){ cout <<tmp->val <<endl; tmp = tmp->next; } return 0;}
0 0
- [leetcode][list] Reorder List
- [leetcode][list] Reorder List
- Leetcode: Reorder List
- [LeetCode] Reorder List
- LeetCode题解:Reorder List
- Leetcode: Reorder List
- LeetCode:Reorder List
- leetcode之Reorder List
- Leetcode: Reorder List
- [LeetCode]Reorder List
- [LeetCode] Reorder List
- leetcode Reorder List
- LeetCode | Reorder List
- LeetCode Reorder List
- LeetCode 之 Reorder List
- Leetcode: Reorder List
- LeetCode OJ:Reorder List
- Reorder List (LeetCode)
- CRT detected that the application wrote to memory after end of heap buffer
- 三步学会Java Socket编程(一)
- 图表标题的表示方法、坐标轴
- 在T-SQL语句中访问远程数据库(openrowset/opendatasource/openquery)
- EL表达式详解教程
- 【Leetcode】Reorder List
- ovs的删除
- 浅析Java中的final关键字
- 说说 sizeof
- OpenGL光照和材质
- css的排版定位机制
- Windows核心编程--Unicode与ANSI
- JDBC的使用五大步骤以及查询操作-数据库编程(二)
- Xcode小技巧:使用代码块+查看某行代码作者+运行时显示控件边框