題目鏈接如下:Leetcode 21
大致描述一下題目:
將兩個有序鏈表合併成一個新的鏈表並返回,拼接給定兩個鏈表的所有節點。
解題思路:
基本的鏈表操作,在這裏複習一下鏈表插入元素的操作。
附上代碼如下(C++):
/*******************************************************************************
Copyright © 2018-20xx Qiao Chuncheng, All Rights Reserved.
File name: 021[合併兩個有序鏈表].cpp
Author: Qiao Chuncheng
Version: v1.0
Date: 2018-04-13
*******************************************************************************/
/**
* 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) {
typedef struct ListNode *List;
List l, s;
l = (List)malloc(sizeof(struct ListNode));
List temp1 = l1;
List temp2 = l2;
List temp = l;
while (temp1&&temp2)
{
if (temp1->val < temp2->val)
{
temp->next = temp1;
temp1 = temp1->next;
temp = temp->next;
}
else
{
temp->next = temp2;
temp2 = temp2->next;
temp = temp->next;
}
}
while (temp1 != NULL)
{
temp->next = temp1;
temp1 = temp1->next;
temp = temp->next;
}
while (temp2 != NULL)
{
temp->next = temp2;
temp2 = temp2->next;
temp = temp->next;
}
temp1 = NULL;
temp2 = NULL;
temp->next = NULL;
//移除表頭元素
s = l;
l = l->next;
free(s);
return l;
}
};