zoukankan      html  css  js  c++  java
  • [LeetCode] #21 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.

    本题就是简单的链表合成。时间:14ms

    我的代码:

    /**
    * 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;
            if (l2 == NULL)
                return l1;
            ListNode *p1, *p2, *pHead, *pNext;
            p1 = l1, p2 = l2, pHead = pNext;
            while (p1!=NULL&&p2!=NULL){
                if (p1->val <= p2->val){
                    pNext->next = p1;
                    p1 = p1->next;
                }
                else{
                    pNext->next = p2;
                    p2 = p2->next;
                }
                pNext = pNext->next;
            }
            while (p1!=NULL){
                pNext->next = p1;
                p1 = p1->next;
                pNext = pNext->next;
            }
            while (p2!=NULL){
                pNext->next = p2;
                p2 = p2->next;
                pNext = pNext->next;
            }
            return pHead->next;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    java数据类型
    索引的种类和优缺点
    IntelliJ IDEA 自动导入快捷键
    KTV点歌系统------LinkedList
    KTV 点歌系统------ArrayList
    超市购物程序
    awk 入门教程
    Git 分支开发规范
    私有镜像仓库Harbor设置https、http访问
    私有镜像仓库Harbor部署
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4452573.html
Copyright © 2011-2022 走看看