Structure of Ordered linked list
Class listnode {int val; listnode nextnode; // constructor listnode (INT Val) {This. val = val; this. nextnode = NULL ;}} public static listnode buildlistnode (INT [] list) {// create three temporary listnode first = NULL, last = NULL, newnode; for (INT I = 0; I <list. length; I ++) {newnode = new listnode (list [I]); If (first = NULL) {First = newnode; last = newnode;} else {last. nextnode = newnode; last = newnode;} return first ;}
Simple printing of ordered linked lists:
int[] a=new int[]{1,5,6};ListNode alist=buildListNode( a); ListNode testnode = alist; while(testnode != null) { System.out.println("-->" + testnode.val); testnode=testnode.nextNode; }
-->1-->5-->6
Interview Question 1:
Combine Two ordered linked lists into a new ordered linked list and return it. The new linked list is composed of all nodes of the given two linked lists.
Example:
Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = null; if (l1.val <= l2.val){ head = l1; head.next = mergeTwoLists(l1.next, l2); } else { head = l2; head.next = mergeTwoLists(l1, l2.next); } return head; }}
Interview Question 2:
Two linked lists are provided: 3-> 1-> 5-> null and 5-> 9-> 2-> null. the return value is 8-> 0-> 8-> null.
public static ListNode addList(ListNode list1,ListNode list2){ ListNode pre=null; ListNode last=null,newNode=null; ListNode result=null; int val=0; int carry=0; while(list1!=null||list2!=null){ val=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)%10; carry=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)/10; list1=list1==null?null:list1.nextNode; list2=list2==null?null:list2.nextNode; newNode=new ListNode(val); if(pre==null){ pre=newNode; last=newNode; }else{ last.nextNode=newNode; last=newNode; } } if(carry>0){ newNode=new ListNode(carry); last.nextNode=newNode; last=newNode; } return pre; }
Ordered linked list basics and interview questions