Merge Two Sorted Lists - Leetcode
来源:互联网 发布:软件测试面试题 编辑:程序博客网 时间:2024/05/29 12:51
题意:合并两个有序链表。
思路:此题难易程度是easy,在数据结构书中讲链表这一块有这个题目出现。做法很简单,分别用指针指向两个链表,比较指针所指的值大小,将值小的那一项放入新链表中,并将该指针向后移动一位。
笔者第一次提交的代码如下。这段代码是有问题的,他用r指针确实按从小到大的顺序遍历的两个链表的元素,head也确实是所谓新链表的头指针的内容。但这里最大的问题是并没有生成完整的链表!head的next指针是NULL,r也只是按从小到大顺序,依次是当前的节点(val,NULL)。但是并没有将每个节点串连起来!这是一个严重的问题。然而这个错误出现之后,笔者并没有弄清状况,仍然不知道代码哪里的错误导致了这样的结果。可见笔者对指针这一块内容理解的过于肤浅了。随后在网上看了一下其他人按照这种做法编写的代码,比照了,然后找出来问题出在哪里。
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head=NULL; ListNode* r=NULL; if (l1 == NULL&&l2 == NULL) return NULL; if (l1 != NULL&&l2 == NULL) return l1; if (l1 == NULL&&l2 != NULL) return l2; if (l1->val<l2->val) { head=new ListNode(l1->val); l1 = l1->next; } else { head = new ListNode(l2->val); l2 = l2->next; } //错误。应该是r=head; head= r; while (l1 != NULL&&l2 != NULL) { if (l1->val<l2->val) { //错误。如果这里重新new一个结点的话,那么r就指向了一个新地址 //因此这样就不能形成一个完整的链表了。 r = new ListNode(l1->val); l1 = l1->next; r = r->next; } else { r = new ListNode(l2->val); l2 = l2->next; r = r->next; } } if (l1 != NULL&&l2 == NULL) { r = l1; } else if (l1 == NULL&&l2 != NULL) { r = l2; } return head; }
修改之后的代码如下。这样就AC了。
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head=NULL; ListNode* r=NULL; if (l1 == NULL&&l2 == NULL) return NULL; if (l1 != NULL&&l2 == NULL) return l1; if (l1 == NULL&&l2 != NULL) return l2; if (l1->val<l2->val) { head=new ListNode(l1->val); l1 = l1->next; } else { head = new ListNode(l2->val); l2 = l2->next; } r = head; while (l1 != NULL&&l2 != NULL) { if (l1->val<l2->val) { r->next = l1; l1 = l1->next; r = r->next; } else { r->next = l2; l2 = l2->next; r = r->next; } } if (l2 == NULL) { r->next=l1; } else if (l1 == NULL) { r->next=l2; } return head; }
1 0
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- Leetcode Merge Two Sorted Lists
- YII2 SQL 基础查询
- Android使用JSON与服务器交互
- Unicode编码转换工具
- zcmu1653
- ubuntu+Qt+OpenGL的环境问题
- Merge Two Sorted Lists - Leetcode
- Scala正则表达式提取文档中任意数字
- javascript倒计时
- URL网络资源下载
- 华为 单板硬件开发 2016校招
- TCP/IP协议 三次握手与四次挥手
- 安卓——ListView的动态添加与删除
- JavaScript应用程序设计:使用Node、HTML5和现代JavaScript类库打造稳健的Web应用——互动出版网
- HDU 5115 Dire Wolf(区间DP)