您的位置:首页 > 其它

《leetCode》:Merge Two Sorted Lists

2015-11-02 22:28 344 查看

题目

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.


思想比较简单:利用两个指针遍历两个链表,并比较将较小的值进行保存。

实现代码如下:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
int my_length(struct ListNode *list){
if(list==NULL){
return 0;
}
int len=1;
while(list->next!=NULL){
len++;
}
return len;
}
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if(l1==NULL){
return l2;
}
if(l2==NULL){
return l1;
}
//先求这两个链表的长度
// int len1=my_length(l1);
// int len2=my_lenght(l2);
//开辟一个来保存返回值
struct ListNode *newHead=(struct ListNode *)malloc(sizeof(struct ListNode));
if(newHead==NULL){
exit(EXIT_FAILURE);
}
struct ListNode *node1=l1;
struct ListNode *node2=l2;
struct ListNode *cur=newHead;
int len=0;
//遍历两个链表,并比较,将较小的值依次放入连接起来
while(node1!=NULL&&node2!=NULL){
int value1=node1->val;
int value2=node2->val;
if(value1<=value2){
cur->next=node1;
node1=node1->next;
}
else{
cur->next=node2;
node2=node2->next;
}
cur=cur->next;
}
//这两个if就是将两个链表中其中一个没有连接完的链表中剩余的结点连接起来
if(node1!=NULL){
cur->next=node1;
cur=cur->next;
node1=node1->next;
}
if(node2!=NULL){
cur->next=node2;
cur=cur->next;
node2=node2->next;

}
return newHead->next;//由于newHead并没有保存结点,而是从newHead->next才开始保存结点的。
}


AC结果如下:Runtime:4ms

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: