21. Merge Two Sorted Lists
来源:互联网 发布:js点击加载更多的例子 编辑:程序博客网 时间:2024/05/17 01:45
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题目很简单,就是直接把两个已经排列的链表进行合并。吐槽一下题目真的不严谨,升序还是降序都没讲。我的做法是新建一个ListNode指针position,然后通过循环比较两个List上的val值,然后链表下一个位置就指向小的值的List上。最后还得判断哪个List先循环完,然后把另一个链上剩下的元素也要合并,而且这些值肯定是有序的了。
Code:
/** * 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) { ListNode list(INT_MAX); ListNode *position = &list; while (l1 != NULL && l2 != NULL) { if (l1 -> val < l2 -> val) { position -> next = l1; l1 = l1 -> next; } else { position -> next = l2; l2 = l2 -> next; } position = position -> next; } if (l1 == NULL) { position -> next = l2; } else { position -> next = l1; } return list.next; }};
阅读全文
0 0
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 使用C/C++实现Socket聊天程序
- Qt编程环境搭建
- C++ 宏定义
- Jquery选择器总结二
- HDS
- 21. Merge Two Sorted Lists
- mysql主从配置
- 类的继承
- caioj.1041 简单的搜索剪枝
- 机器学习西瓜书-学习笔记1
- #Swing#
- 短实训-数据库基础(一)
- jquery事件
- JSP基础知识(cookie和session)