日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

剑指offer之合并已排序链表(递归实现)

發布時間:2023/12/4 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 剑指offer之合并已排序链表(递归实现) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 問題

合并2個已經排好序的鏈接,比如

1->3->5->7

2->4->6

合并后新的鏈表如下

1->2->3->4->5->6->7

?

?

?

?

?

?

?

?

2 代碼實現

#include <stdio.h> typedef struct Node {int val;struct Node *next; } Node;/**print list*/ void print_list(Node *head) {if (head == NULL){printf("head is NULL\n");return;}Node *p = head;while (p != NULL){printf("value is %d\n", p->val);p = p->next;} }/**合并鏈表*/ struct Node* merge(Node *head1, Node *head2) {if (head1 == NULL){return head2;}if (head2 == NULL){return head1;}struct Node *new = NULL;if (head1->val < head2->val){new = head1;new->next = merge(head1->next, head2);}else {new = head2;new->next = merge(head1, head2->next);}return new; }int main() {//list1 0->3->5->9;Node head, node1, node2, node3;head.val = 0;head.next = &node1;node1.val = 3;node1.next = &node2;node2.val = 5;node2.next = &node3;node3.val = 9;node3.next = NULL;printf("list1 is such as\n");print_list(&head);//list2 1->4->6Node head1, node4, node5;head1.val = 1;head1.next = &node4;node4.val = 4;node4.next = &node5;node5.val = 6;node5.next = NULL;printf("list2 is such as\n");print_list(&head1);printf("merge list1 and list2\n");Node *new = merge(&head, &head1);print_list(new);return 0; }

?

?

?

?

?

?

?

3 運行結果

list1 is such as value is 0 value is 3 value is 5 value is 9 list2 is such as value is 1 value is 4 value is 6 merge list1 and list2 value is 0 value is 1 value is 3 value is 4 value is 5 value is 6 value is 9

?

?

?



4 總結

我一開始寫成這樣了

struct Node* merge(Node *head1, Node *head2) {if (head1 == NULL){return head2;}if (head2 == NULL){return head1;}struct Node *new = NULL;while (head1 != NULL && head2 != NULL) {if (head1->val < head2->val){new = head1;new->next = merge(head1->next, head2);}else {new = head2;new->next = merge(head1, head2->next);}}return new; }

加了while循環?又是遞歸,肯定容易出問題,一定要記住,遞歸函數里面循環體里面又有遞歸一般就有問題

?

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的剑指offer之合并已排序链表(递归实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。