合并二个有序链表:
逐步遍历链表A,B,同时比较A,B对应位置的属性值大小,将属性值较小的节点加入新链表,直到链表A,B遍历完毕;
/**
* 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)
{
ListNode *res=(ListNode*)malloc(sizeof(ListNode));
res->next=NULL;
ListNode *ans=res;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<l2->val)
{
ans->next=l1;
ans=ans->next; //add new node into the res
l1=l1->next;//l1 the next node
}
else
{
ans->next=l2;
ans=ans->next; // add new node into the res
l2=l2->next;//l2 the next node
}
}
if(l1==NULL)
ans->next=l2;
else
ans->next=l1; //add the rest nodes into the res
return res->next;
}
};
本文介绍了一种合并两个已排序的单链表的方法,通过比较两链表节点的值,构造新的有序链表。该算法适用于计算机科学中的数据结构操作,特别是链表处理。
2万+

被折叠的 条评论
为什么被折叠?



