首页 > 其他 > 详细

将链表中元素值两两交换(比如1,2,3,4,5变为2,1,4,3,5)

时间:2020-03-26 15:40:39      阅读:89      评论:0      收藏:0      [点我收藏+]
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct node
 5 {
 6     int data;
 7     node *next;
 8 } node;
 9 
10 // 插入数组元素值
11 node *insert(node *L, int datas[], int len)
12 {
13     node *temp = L;
14     for (int i = 0; i < len; i++)
15     {
16         node *p = (node *)malloc(sizeof(node));
17         p->next = NULL;
18         p->data = datas[i];
19         temp->next = p;
20         temp = p;
21     }
22 }
23 
24 // 交换
25 node *reverse(node *L)
26 {
27     if (L == NULL)
28         return NULL;
29     if (L->next == NULL)
30         return L;
31     node *next = L->next;
32     L->next = reverse(next->next); // 递归交换
33     next->next = L;
34     return next;
35 }
36 int main()
37 {
38     node *L = (node *)malloc(sizeof(node)), *r;
39     int a[] = {2, -1, 3, -4, 8, -7, 6};
40     L->next = NULL;
41     insert(L, a, 7);
42     r = reverse(L->next);
43     for (node *q = r; q; q = q->next)
44         printf("%d ", q->data);
45     return 0;
46 }

 

将链表中元素值两两交换(比如1,2,3,4,5变为2,1,4,3,5)

原文:https://www.cnblogs.com/sqdtss/p/12574612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!