双链表偶数节点求和java_编写一个重新排列链表的函数,将节点置于列表中奇数位置的节点之后的偶数位置...

在下文中,每次调用swap_nodes时,另一个奇数下沉到最后一个沉没奇数。每次迭代时,均匀组合在一起,它们会冒泡到列表的末尾。这是一个例子:

/*

[0]-1-2-3-4-5

1-[0-2]-3-4-5

1-3-[0-2-4]-5

1-3-5-[0-2-4]

*/

#include

#include

#define LIST_LENGTH 10

struct node{

int id;

struct node *next;

};

void print_list(struct node *current)

{

while(NULL != current){

printf("node id = %d\n",current->id);

current = current->next;

}

printf("Done\n");

}

struct node *swap_nodes(struct node *head_even, struct node *tail_even, struct node *next_odd)

{

tail_even->next = next_odd->next;

next_odd->next = head_even;

return next_odd;

}

struct node *reorder_list(struct node *head)

{

struct node *head_even;

struct node *tail_even;

struct node *next_odd;

struct node *last_odd;

if(NULL == head->next){

return head;

}

head_even = head;

tail_even = head;

next_odd = head->next;

last_odd = head->next;

head = swap_nodes(head_even, tail_even, next_odd);

if(NULL != tail_even->next){

tail_even = tail_even->next;

}

while (NULL != tail_even->next) {

next_odd = tail_even->next;

last_odd->next = swap_nodes(head_even, tail_even, next_odd);

last_odd = last_odd->next;

if(NULL != tail_even->next){

tail_even = tail_even->next;

}

}

return head;

}

int main(void)

{

int i;

struct node *head = (struct node *) malloc(LIST_LENGTH*sizeof(struct node));

struct node *mem = head;

if(NULL == head){

return -1;

}

struct node *current = head;

for(i=0;i

current->next = current + 1;

current->id = i;

current = current->next;

}

current->next = NULL;

current->id = i;

head = reorder_list(head);

print_list(head);

free(mem);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值