Merge Two Sorted Lists
来源:互联网 发布:js实现日期时间 编辑:程序博客网 时间:2024/06/10 22:52
/** * 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* head ; ListNode* p1 = l1 ; ListNode* p2 = l2; int length1 =0 , length2 =0 ; //特殊情况处理 if(l1 == NULL){ return l2; } if(l2 == NULL){ return l1; } //记录长度 //p1=l1; // p2=l2; while(p1 != NULL){ p1 = p1->next; length1++; } while(p2 !=NULL){ p2 = p2->next; length2++; } //决定谁是head,并把指针位置修改 if(l1->val < l2->val){ head = l1; p1 = l1->next; p2 = l2; } else{ head = l2; p2 = l2->next; p1 = l1; } ListNode *temp = head; while(p1 != NULL && p2 != NULL){ if(p1->val < p2->val){ temp->next = p1; //一开始没有移动temp,导致只有两个首尾两个数。 temp = p1; p1 = p1->next; } else{ temp->next = p2; //一开始没有移动temp,导致只有两个首尾两个数。 temp = p2; p2 = p2->next; } } if(p1 == NULL){ temp->next = p2; } else{ temp->next = p1; } return head; }};
0 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Git的使用
- SourceInsight快捷键集合
- jffs2文件系统的制作和移植
- codeblocks支持c++11新标准
- DAY10结业作业-简单的个人博客
- Merge Two Sorted Lists
- 会话技术cookie
- Java中的23种设计模式与7大原则
- ALV 简单实现HTML抬头的方法 (介绍 二)
- it is not safe to rely on the system
- Strut2和SpringMVC区别
- spring理解
- Tomcat+redis+nginx配置
- 步进电机S曲线的生成