Java implementation merges two sorted list instance code _java

Source: Internet
Author: User

One of the biggest features of Java, compared to C + +, is the absence of confusing pointers, but we cannot deny that pointers do count as a razor in certain situations. Although the pointer is not explicitly defined in Java, because of the class idea, we can use class to implement the operation of the pointer. Waiter, Shangli-----Merges two sorted lists, outputs the header nodes of the merged list, and the elements in the merged list are ordered.

It takes time to keep in mind: In Java, a node in a list is actually an object of a class instantiation.

The sample code is as follows:

Copy Code code as follows:

Package DecemberOf2013;

Class listnode{
int Val;
ListNode Next;
Public ListNode (int val) {
This.val = val;
This.next = null;
}
}

public class Mergetowsortedlists {

Public ListNode mergelists (listnode L1, ListNode L2) {

ListNode p1 = L1;
ListNode P2 = L2;

ListNode fadehead = new ListNode (0);
ListNode phead = Fadehead;

while (P1!= null && p2!= null) {
if (p1.val <= p2.val) {
Phead.next = p1;
P1 = P1.next;
}
else{
Phead.next = p2;
P2 = p2.next;
}
Phead = Phead.next;
}

if (P1!= null) {
Phead.next = p1;
}
else{
Phead.next = p2;
}

return fadehead.next;
}
}

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.