Untitled
unknown
java
a year ago
2.3 kB
9
Indexable
public class Solution { public ListNode combineLists(ListNode oddListHead, ListNode evenListHead){ ListNode result = new ListNode(-1); ListNode tempNode=result; while(oddListHead!=null && evenListHead!=null){ tempNode.next=oddListHead; oddListHead=oddListHead.next; tempNode=tempNode.next; tempNode.next=evenListHead; evenListHead=evenListHead.next; tempNode=tempNode.next; } while(oddListHead!=null) { tempNode.next=oddListHead; oddListHead=oddListHead.next; } return result.next; } public ListNode reverse(ListNode head) { ListNode prev=null; ListNode curr=head; while(curr!=null) { ListNode nextNode=curr.next; curr.next=prev; prev=curr; curr=nextNode; if(nextNode!=null) { nextNode=nextNode.next; } } return prev; } public int getSizeOfLL(ListNode head){ int count=0; ListNode tempNode=head; while(tempNode!=null) { tempNode=tempNode.next; count++; } return count; } public void printList(ListNode head) { ListNode tempNode = head; while(tempNode!=null) { System.out.print(tempNode.val+" "); tempNode=tempNode.next; } } public ListNode evenReverse(ListNode head) { //You can code here if(getSizeOfLL(head)<=3) { return head; } ListNode oddListHead=head; ListNode evenListHead=head.next; ListNode oddPtr=oddListHead; ListNode evenPtr=evenListHead; while(oddPtr!=null && oddPtr.next!=null && evenPtr!=null && evenPtr.next!=null) { ListNode nextOddNode=oddPtr.next.next; ListNode nextEvenNode=evenPtr.next.next; oddPtr.next=nextOddNode; oddPtr=oddPtr.next; evenPtr.next=nextEvenNode; evenPtr=evenPtr.next; } while(oddPtr!=null) { ListNode nextOddNode=null; oddPtr.next=nextOddNode; oddPtr=oddPtr.next; } evenListHead=reverse(evenListHead); // printList(evenListHead); // System.out.println(); // printList(oddListHead); return combineLists(oddListHead,evenListHead); } }
Editor is loading...
Leave a Comment