链接: https://oj.leetcode.com/problems/merge-two-sorted-lists/
题目要去把两个有序的链表合并,并且合并后的链表依然有序.
/** * 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 *t1=l1; ListNode *t2=l2; ListNode *ans=new ListNode(0); //哨兵 ListNode *ta=ans; while(t1&&t2) { if(t1->val<t2->val) { ta->next=t1; t1=t1->next; ta->next->next=NULL; } else { ta->next=t2; t2=t2->next; ta->next->next=NULL; } ta=ta->next; } if(t1==NULL&&t2!=NULL) ta->next=t2; if(t2==NULL&&t1!=NULL) ta->next=t1; ans=ans->next; return ans; } };
天下武功,唯快不破