简体   繁体   中英

Java : Merging two sorted linked lists

I have developed a code to merge two already sorted linked lists in java.

I need help with the following:

  1. How do I retain the value of head node of merged list without using tempNode?
  2. Can this code be better optimized?

     public static ListNode mergeSortedListIteration(ListNode nodeA, ListNode nodeB) { ListNode mergedNode ; ListNode tempNode ; if (nodeA == null) { return nodeB; } if (nodeB == null) { return nodeA; } if ( nodeA.getValue() < nodeB.getValue()) { mergedNode = nodeA; nodeA = nodeA.getNext(); } else { mergedNode = nodeB; nodeB = nodeB.getNext(); } tempNode = mergedNode; while (nodeA != null && nodeB != null) { if ( nodeA.getValue() < nodeB.getValue()) { mergedNode.setNext(nodeA); nodeA = nodeA.getNext(); } else { mergedNode.setNext(nodeB); nodeB = nodeB.getNext(); } mergedNode = mergedNode.getNext(); } if (nodeA != null) { mergedNode.setNext(nodeA); } if (nodeB != null) { mergedNode.setNext(nodeB); } return tempNode; } 

1: You have to keep a record of the first node, which means you will have to store it in a variable such as tempNode .

2: No. There's not much to optimize here. The process is quite trivial.

There are a few possibilities:

1) Instead of using mergedNode to keep track of the previous node, use nodeA.getNext().getValue() and nodeB.getNext().getValue() . Your algorithm will become more complex and you will have to deal with a few edge cases, but it is possible to eliminate one of your variables.

2) Use a doubly linked-list, and then use either nodeA.getPrev().getValue() and nodeB.getPrev().getValue() instead of mergedNode . You will also have to deal with edge cases here too.

In order to deal with edge cases, you will have to guarantee that your references can not possibly be null before calling getPrev() , getNext() or getValue() , or else you will throw an exception.

Note that the above modifications sacrifice execution time slightly and (more importantly) simplicity in order to eliminate a variable. Any gains would be marginal, and developer time is far more important than shaving a microsecond or two off of your operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM