题目链接如下: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; } };