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;
}
}