Reorder List

来源:互联网 发布:多合一建站源码 编辑:程序博客网 时间:2024/06/09 21:01

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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
原创粉丝点击