• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

技术天地

合并排好序的两个链表

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/2018/1012/69.html

今天我们常州网页设计工作室幻天网络来教大家合并链表技术,原理很简单,直接上代码吧。
 

 

/**

 * 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 *head = new ListNode(0), *p = head;

        while(l1 && l2)

        {

            if(l1->val < l2->val)

            {

                p->next = l1;

                l1 = l1->next;

            }

            else

            {

                p->next = l2;

                l2 = l2->next;

            }

            p = p->next;

        }

        if(l1)

            p->next = l1;

        else

            p->next = l2;

        head = head->next;

        return head;

    }

};



上篇:上一篇:二叉树的基本操作
下篇:下一篇:单链表逆序的几种方法