Interview question 17: Merge two sorted lists

Source: Internet
Author: User

Title Description:

Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.
(Hint: Be sure to use a linked list.) )

input:

The input may contain multiple test samples, The input ends with EOF.
For each test case, enter the first behavior of two integers n and m (0<=n<=1000, 0<=m<=1000): N represents the number of elements of the first linked list that will be entered, and M represents the number of elements of the second linked list to be entered.
The following line includes n number t (1<=t<=1000000): Represents the element in the chain table one. The next line contains m elements, s (1<=t<=1000000).

Output:

corresponding to each test case,
If there is a result, output the corresponding linked list. Otherwise, the output is null.

Sample input:
5 21 3 5 7 92 40 0
Sample output:
1 2 3 4 5 7 9NULL
Problem-solving ideas: The problem of the solution of the idea is relatively simple, the general data structure of the book, there is no longer repeat. The test center is not a merger of the idea, but to examine the candidate's ability to analyze the problem (whether the formation of a very clear thinking, pointer operation Proficiency) and the candidate can write strong code. Java code:
Import Java.io.ioexception;import Java.io.StreamTokenizer; public class Main {public static void main (string[] args) throws IOException {//TODO auto-generated Method St        UB Streamtokenizer stin = new Streamtokenizer (system.in);        int m, n,value;            while (Stin.nexttoken ()! = streamtokenizer.tt_eof) {m = (int) stin.nval;            Stin.nexttoken ();            n = (int) stin.nval;            if (m = = 0 && n==0) System.out.println ("NULL");                else {ListNode head1 = null;                ListNode head2 = null;                ListNode p = null;                    for (int i = 0; i < m; i++) {//Initialize linked list Stin.nexttoken ();                    Value = (int) stin.nval;                        if (i = = 0) {head1 = new ListNode ();                        Head1.value = value;                        Head1.next = null;                    p = head1;    } else {                    ListNode pnode = new ListNode ();                        Pnode.value = value;                        Pnode.next = null;                        P.next = Pnode;                    p = pnode;                    }} for (int i = 0; i < n; i++) {//Initialize list stin.nexttoken ();                    Value = (int) stin.nval;                        if (i = = 0) {head2 = new ListNode ();                        Head2.value = value;                        Head2.next = null;                    p = head2;                        } else {ListNode pnode = new ListNode ();                        Pnode.value = value;                        Pnode.next = null;                        P.next = Pnode;                    p = pnode;                }} ListNode Head=merge (Head1, head2);                p = head; while (p!= null && p.next! = null) {System.out.print (P.value + "");                p = p.next;                } System.out.print (P.value);            System.out.println ();            }}} public static ListNode merge (ListNode Head1,listnode head2) {if (head1 = = null)        return head2;         else if (head2 = = null) return head1;        ListNode head = null;            if (Head1.value < Head2.value) {head = Head1;        Head.next=merge (Head1.next, head2);            } else {head = head2;        Head.next=merge (Head1, Head2.next);    } return head;    }}class ListNode {int value; ListNode Next;}
C + + code
#include <stdio.h> using namespace std;    Class Linknode{public:int Val;         Linknode *next;  Linknode (): Val (0), next (NULL) {}; };         linknode* retrievelist (int n) {int val;         if (n <= 0) return NULL;    Linknode *head = NULL;    Linknode *cur = NULL;                     for (int i = 0; i < n; ++i) {scanf ("%d", &val);            if (head = = NULL) {head = new Linknode ();            cur = head;        Cur->val = val;            } else{Cur->next = new Linknode ();            Cur = cur->next;        Cur->val = val; }} return head;        void Printanddestroylist (linknode* head) {if (head = = NULL) {printf ("null\n");    Return    } Linknode *cur = head;                     while (cur) {printf ("%d", cur->val);        Cur = cur->next;        Delete head;                  head = cur;    if (cur) printf (""); } printf ("\ n");} linknode* mergelist (linknode* head1,linknode* head2) {linknode* head = NULL;    linknode** cur = &head;            while (Head1 && head2) {if (Head1->val <= head2->val) {*cur = Head1;        Head1 = head1->next;            } else{*cur = head2;        Head2 = head2->next;    } cur = & ((*cur)->next);    } if (Head1 | | head2) {*cur = head1? head1:head2;    } return head;         } int main (void) {int n, m;                 while (scanf ("%d", &n)! = EOF) {scanf ("%d", &m);        Linknode *head1 = retrievelist (n);                 Linknode *head2 = retrievelist (m);                 linknode* head = mergelist (Head1, head2);    Printanddestroylist (head); } return 0;}
C Code:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{int data; struct node *next;}  Linknode;           Linknode *initlinklist (Linknode *l) {L = (Linknode *) malloc (sizeof (Linknode));    if (null = = L) {return null;          } l->next = NULL;  return L;}    Linknode *createlinklist (linknode *l, int n) {Linknode *tail = L;          Linknode *p = NULL;        while (n--) {p = (Linknode *) malloc (sizeof (Linknode));        scanf ("%d", &p->data);        Tail->next = p;    tail = p;          } tail->next = NULL;  return L;}    Linknode *mergelinklist (Linknode *la, Linknode *lb) {Linknode *tmp = LA;     Linknode *pa = la->next;          Linknode *PB = lb->next;            while (Pa!=null && pb!=null) {if (Pa->data < pb->data) {tmp->next = PA;            TMP = PA;        PA = pa->next;          } else {  Tmp->next = PB;            TMP = PB;           PB = pb->next; }} Tmp->next = PA? PA:PB;  /*tmp direct pointing to the remainder */return LA;}          void Printlinklist (Linknode *l) {Linknode *p = L;        while (p->next! = NULL) {if (P! = L) {printf ("");        } p = p->next;    printf ("%d", p->data);  } printf ("\ n");}          void Destroylinklist (Linknode *l) {Linknode *p = l->next;        while (P! = NULL) {L->next = p->next;         Free (p);    p = l->next;    } free (L);  L = NULL;}          int main (void) {int n, m;        while (scanf ("%d%d", &n, &m)! = EOF) {if (m+n = = 0) {printf ("null\n");            } else {Linknode *la = NULL;            Linknode *lb = NULL;            La = Initlinklist (LA);                            LB = initlinklist (lb);        La = Createlinklist (LA, N);    LB = createlinklist (lb, m);            La = Mergelinklist (LA, LB);              Printlinklist (LA); Destroylinklist (LA); /* Because a points to B in the process of linking, with the B released */}} return 0;}
Test Case: Functional test: Enter two linked lists have multiple nodes, node values are different or there are multiple nodes with equal values. Special input test: two lists have a null pointer in the list, and only one node in the two linked list. Experience: I think, for this topic must do their own hands, not only satisfied with the formation of ideas, often handwritten code, commonly used code to be able to easily pick up, and there is no error.

Interview question 17: Merge two sorted lists

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.