笔试题34. LeetCode OJ (21)
来源:互联网 发布:php rename 移动文件 编辑:程序博客网 时间:2024/06/05 22:32
已经已连续做了好几道题了,感觉停不下来了,突然来了兴趣了,这个题让我觉得思路很清晰,合并两个排序的链表。我的思路如下:分别从两个链表里面摘取节点放到新的链表中,最后摘到一个也不留就行了。不过需要注意的是一些小细节,主要的注意事项如下:
1.两空(两个空的链表)
2.一空(一个链表为空一个部位空)
3.一个摘完了,另外的可能还有节点(这个需要好好注意一下,很容易出错的)
好了,见代码吧:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { //类似于从两个链表上取下节点,放到newHead中去 if(l1 == NULL && l2 == NULL) { return NULL; } if(l1 == NULL) { return l2; } if(l2 == NULL) { return l1; } ListNode * newHead=NULL; if(l1->val <= l2->val) { newHead=l1; l1=l1->next; } else { newHead=l2; l2=l2->next; } newHead->next = NULL; ListNode *cur = newHead; while(l1 && l2) { if(l1->val <= l2->val) { cur->next = l1; l1=l1->next; } else { cur->next = l2; l2 = l2->next; } cur=cur->next; cur->next=NULL; } if(l1) {//说明 l2 完了,只剩 l1 了 cur->next = l1; } if(l2) {//说明 l1 完了,只剩 l2 了 cur->next=l2; } return newHead; }};结果如下:
1 0
- 笔试题34. LeetCode OJ (21)
- 笔试题21 . LeetCode OJ (8)
- 笔试题14. LeetCode OJ (1)
- 笔试题15. LeetCode OJ (2)
- 笔试题16. LeetCode OJ (3)
- 笔试题17. LeetCode OJ (4)
- 笔试题18. LeetCode OJ (7)
- 笔试题19. LeetCode OJ (5)
- 笔试题20. LeetCode OJ (6)
- 笔试题22. LeetCode OJ (9)
- 笔试题23. LeetCode OJ (10)
- 笔试题24. LeetCode OJ (11)
- 笔试题25. LeetCode OJ (12)
- 笔试题26. LeetCode OJ (13)
- 笔试题27. LeetCode OJ (14)
- 笔试题28. LeetCode OJ (15)
- 笔试题29. LeetCode OJ (16)
- 笔试题30. LeetCode OJ (17)
- JQuery-layer web弹窗层
- 软件开发公司必须具备的环境软件
- 从头开始学习
- CC2640 multi_role 工程作为主机无法接收从机的notify
- 简单数据结构---数组实现栈
- 笔试题34. LeetCode OJ (21)
- Mongodb aggregate group DBRef类型,并处理返回的DBRef数据Demo
- RCNN
- 中国广电将成第四运营商
- Swift 代码调试-善用XCode工具(UI调试,五种断点,预览UIImage...)
- android注入之ButterKnife的使用
- 拉普拉斯锐化处理
- 获取android keystore的SHA1值
- iOS开发系列--UITableView全面解析