Merge two sorted lists
- Number of participants: 1527 time limit: 1 seconds space limit: 32768K
- By scale: 27.96%
- Best record: 0 ms|8552k(from No. 708854 kn)
The title describes the input of two monotonically increasing lists, the output of the list of two linked lists, of course, we need to synthesize the linked list to meet monotonic rules.
Topic Link:http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?rp=1&ru=/ta/coding-interviews& Qru=/ta/coding-interviews/question-ranking
Chain list exercise, define a pointer p, from small to large once added, when one of the list is empty point to another chain list, and then exit, return the list of the head pointer (I define the list has a head pointer, so return to Q->next on it.) )
For a long time did not touch the pointer and linked list, first brush from the basic problem. (There are also many linked list operations, including the procedure to change the error is also a pointer)
In the ongoing update.
#include <stdio.h> #include <iostream>using namespace std;struct listnode{int val; struct ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};class solution {public:listnode* Merge (listnode* phead1,listnode* pHead2) { if (!PHEAD1) return pHead2; else if (!phead2) return pHead1; ListNode *p,*q; P=new ListNode (NULL); Q=p; while (phead1| | PHEAD2) {if (!phead1&&phead2) {p->next=phead2; P=phead2; Break } if (!phead2&&phead1) {p->next=phead1; P=phead1; Break } if (Phead1->val<phead2->val) {p->next=phead1; P=phead1; phead1=phead1->next; } else {p->next=phead2; P=phead2; Phead2=phead2->next; }} return q->next; } listnode* creatlist (ListNode *phead,int N) {if (n==0) return NULL; ListNode *p,*q; Phead=new ListNode (NULL); P=phead; cin>>p->val; int x; while (--n) {cin>>x; Q=new ListNode (x); p->next=q; p=q; } return phead; }};int Main () {int n,m; Solution so; ListNode *l1,*l2; cin>>n; L1=so. Creatlist (L1,n); cin>>m; L2=so. Creatlist (L2,M); ListNode *ans=so. Merge (L1,L2); while (ans) {printf ("%d\t", ans->val); ans=ans->next; } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Merge two sorted lists (Sword Point offer)