[leetcode] Reorder List
来源:互联网 发布:联网监控软件 编辑:程序博客网 时间:2024/06/08 10:09
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}.
思路:先是将整个链表分割成两部分,将后半部分反转,然后与前半部分合并
输入格式:
4
1 2 3 4
代码如下:
#include<iostream>using namespace std;struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){}};void reorderList(ListNode *head){ if(head==NULL) return; if(head->next==NULL) return; ListNode *slow=head,*fast=head; while(fast->next!=NULL && fast->next->next!=NULL){ slow=slow->next; fast=fast->next->next; } fast=slow->next; slow->next=NULL; ListNode *first,*second; first=fast; second=fast->next; first->next=NULL; ListNode *temp; while(second!=NULL){ temp=second->next; second->next=first; first=second; second=temp; } ListNode *lhalf; lhalf=first; ListNode *p=head; ListNode *q=head; int i=1; q=q->next; while(q!=NULL && lhalf!=NULL){ if(i%2==0){ p->next=q; q=q->next; } if(i%2!=0){ p->next=lhalf; lhalf=lhalf->next; } p=p->next; i++; } if(q!=NULL) p->next=q; else if(lhalf!=NULL) p->next=lhalf;}int main(){ int n,a; cin>>n; ListNode *head,*q; head=(ListNode *)malloc(sizeof(ListNode)); q=head; for(int i=0;i<n;i++){ cin>>a; ListNode *p; p=(ListNode *)malloc(sizeof(ListNode)); p->val=a; q->next=p; q=p; } q->next=NULL; ListNode *first=head->next; reorderList(first); while(first!=NULL){ cout<<first->val<<" "; first=first->next; } cout<<endl; 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)
- 指针函数和函数指针
- Nexus配置详解
- LeetCode - Trapping Rain Water 等雨水的凹槽容量
- PHP Session文件的散列存储及过期删除
- 有关日志
- [leetcode] Reorder List
- log_archive_dest_n和standby_archive_dest
- $q & promise service
- 有线 无线同时使用的相关问题
- Python网络爬虫抓取糗事百科
- Java 8的五大特性,将改变你的代码之路
- HDOJ-1011(树形DP)
- 不忘初心,玉汝于成
- 京东获取订单的接口