Reorder List
来源:互联网 发布:多合一建站源码 编辑:程序博客网 时间:2024/06/09 21:01
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}
.
#include<stdio.h>#include<stdlib.h>typedef struct ListNode{ int val; struct ListNode *next;}ListNode;void reorderList(ListNode *head) { ListNode *p; int i,j,cnt=0; for(p=head;p!=NULL;p=p->next) cnt++; ListNode *arr[cnt]; if(head==NULL || head->next==NULL) return; for(i=0,p=head;p!=NULL;p=p->next,i++){ arr[i]=p; } //for(i=0;i<cnt;i++) printf("%d ",arr[i]->val); for(i=0,j=cnt-1;i<j;i++,j--){ arr[i]->next=arr[j]; arr[j]->next=arr[i+1]; } arr[i]->next=NULL; //for(p=head;p!=NULL;p=p->next) printf("%d ",p->val);}ListNode *createList(){ ListNode *head,*p1,*p2; int data,cnt=0; head=NULL; p1=p2=(ListNode *)malloc(sizeof(ListNode)); scanf("%d",&data); p1->val=data; while(data!=0){ cnt++; if(cnt==1){ head=p1; } else{ p2->next=p1; } p2=p1; p1=(ListNode *)malloc(sizeof(ListNode)); scanf("%d",&data); p1->val=data; } p2->next=NULL; return head;}void main(){ ListNode *head,*p; head=createList(); for(p=head;p!=NULL;p=p->next) printf("%d ",p->val); printf("\n"); reorderList(head);}
0 0
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- flahs释放内存
- 一名初创公司员工的心声
- dayreading2
- POJ 1269 Intersecting Lines
- 电源设计的差模共模问题
- Reorder List
- [LeetCode] Largest Rectangle in Histogram
- 在XP下U盘安装Ubuntu12.04
- CMS1
- 简单插入排序
- 多控制器
- 在微信上,钱可以这么赚
- c++中的左值和右值
- Android 引用库 library导致的问题