/*********************************************
重排链表
输入: head = [1,2,3,4]
输出: [1,4,2,3]
**********************************************/
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* init(int val){
struct ListNode* head = malloc(sizeof(struct ListNode));
head->next = NULL;
head->val = val;
return head;
}
void insert(struct ListNode* head, int val){
struct ListNode* p = head;
while(p->next){
p = p->next;
}
struct ListNode* node = malloc(sizeof(struct ListNode));
node->next = NULL;
node->val = val;
p->next = node;
}
void print(struct ListNode* head){
struct ListNode* p = head;
while(p){
printf("%d ", p->val);
p = p->next;
}
}
void printArray(int *a, int len){
for (int i=0;i<len;i++){
printf("%d ",a[i]);
}
printf("\n");
}
void reorderList(struct ListNode* head){
int len=0;
struct ListNode* p = head;
while(p){
p = p->next;
len++;
}
p = head;
int i=0;
int *a = malloc(sizeof(int)*len);
while(p){
a[i]= p->val;
p = p->next;
i++;
}
printArray(a,len);
i=0;
int j = len-1;
p = head;
int n =0;
while(p){
if (n % 2==0){
p->val = a[i];
i++;
}else{
p->val = a[j];
j--;
}
p = p->next;
n ++;
}
print(head);
}
int main()
{
struct ListNode* head = init(1);
insert(head,2);
insert(head,3);
insert(head,4);
insert(head,5);
insert(head,6);
insert(head,7);
insert(head,8);
insert(head,9);
insert(head,10);
print(head);
printf("\n");
reorderList(head);
return 0;
}
C语言,重排链表
最新推荐文章于 2022-06-17 12:45:27 发布