Browse files

合并两个sorted list

  • Loading branch information...
1 parent 470135b commit 93b20fe4b69d6f8339465bd47c4fd2d64a4fbe61 = committed Feb 14, 2014
Showing with 64 additions and 0 deletions.
  1. +64 −0 merge-two-sorted-lists.cpp
View
64 merge-two-sorted-lists.cpp
@@ -0,0 +1,64 @@
+
+
+// http://oj.leetcode.com/submissions/detail/3657799/
+
+
+// Merge Two Sorted Lists
+
+// 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.
+
+
+/**
+ * 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) {
+ if(l1==NULL) { // 空表判断
+ return l2;
+ }else if(l2==NULL) {
+ return l1;
+ }
+
+ ListNode *newHead = NULL;
+ if(l1->val<=l2->val) { // 判断新表头
+ newHead = l1;
+ l1 = l1->next;
+ }else {
+ newHead = l2;
+ l2 = l2->next;
+ }
+
+ ListNode *node = newHead;
+ while(true) {
+ if(l1==NULL) {
+ node->next = l2;
+ break;
+ }else if(l2==NULL) {
+ node->next = l1;
+ break;
+ }
+
+ if(l1->val<=l2->val){
+ node->next = l1;
+ l1 = l1->next;
+ }else{
+ node->next = l2;
+ l2 = l2->next;
+ }
+ node = node->next;
+ }
+ return newHead;
+ }
+};
+
+
+

0 comments on commit 93b20fe

Please sign in to comment.