<LeetCode OJ> 21. Merge Two Sorted Lists

来源:互联网 发布:两小无猜网络剧资源 编辑:程序博客网 时间:2024/05/04 06:32

21. Merge Two Sorted Lists

My Submissions
Total Accepted: 96394 Total Submissions: 285151 Difficulty: Easy

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.




本题答案参考于讨论区

题目说合并成为一个新的有序链表!
用一个指针始终指向值为最小的链表头,用一个临时指针始终维护两个链表未被调整过的当前“头”的较小者的指向

举例:链表a,1->3->5->7,链表b,2->4->6->8,调整后的顺序:1->2->3->4->5->6->7->8

一,将较小的链表头作为合并后的头

当前状态:head->1,list1->3,list2->2

二,通过维护一个指针调整较小者的指向

tmphead=head;//tmphead始终指向当前有序的最前端

第一次调整:list2的2较小,则将tmphead的下一个指向2

tmphead->next=head;//即1->2

tmphead=list2;//tmphead始终指向当前有序的最前端

list2=list2->next;//准备下一轮比较list2=4


第二次调整:list1的3较小,则将tmphead的下一个指向3

tmphead->next=head;//即2->3

tmphead=list2;//tmphead始终指向当前有序的最前端

list2=list2->next;//准备下一轮比较list1=5

.........

最后记得维护剩余节点

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */  class Solution {public:    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {        if(list1 == NULL)               return list2;          if(list2 == NULL)               return list1;          ListNode* head=NULL;//始终指向新链表的头          ListNode* tmphead=NULL; //维护链表的有序性        //一,将小的链表头作为头          if(list1 -> val < list2 -> val){              head = list1;              list1 = list1 -> next;          }else{              head = list2;              list2 = list2 -> next;          }                 tmphead = head;            //二,调整值较小的节点的指向        while(list1 != NULL && list2 != NULL){              if(list1 -> val < list2 -> val){                  tmphead -> next = list1;                  tmphead = list1;                  list1 = list1 -> next;              }else{                  tmphead -> next = list2;                  tmphead = list2;                  list2 = list2 -> next;              }          }          //三,维护剩余的节点指向        if(list1 != NULL)               tmphead -> next = list1;          if(list2 != NULL)               tmphead -> next = list2;                    return head;      }};

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50358232

原作者博客:http://blog.csdn.net/ebowtang

1 0
原创粉丝点击