标签:merge 一个 link sorted val init public 另一个 ==
题目描述:
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.
分析:
两个已排序链表合并,主要是对链表插入的考查。两个指针指向两个链表头,分别比较两个指针指向值大小,插入新链表中。如果其中一个指针指向为空,则将另一个指针指向的节点直接链入到新链表中。
注意:对于链表的头结点一般在编码时都设置为空,遍历是从head->next节点开始遍历。
代码:
/* * 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) { struct ListNode *first = l1; struct ListNode *second = l2; if(first == NULL) return l2; if(second == NULL) return l1; struct ListNode *mergelist = (struct ListNode*)malloc(sizeof(struct ListNode)); mergelist->val = -1; mergelist->next = NULL; struct ListNode *p = mergelist; while((first != NULL) && (second != NULL)) { if(first -> val < second -> val) { p->next = first; first = first->next; } else { p->next = second; second = second->next; } p = p->next; } if(first != NULL) p->next = first; if(second != NULL) p->next = second; return mergelist->next; } };
标签:merge 一个 link sorted val init public 另一个 ==
原文地址:http://www.cnblogs.com/scu-cjx/p/7373103.html