Untitled
unknown
java
2 years ago
2.1 kB
13
Indexable
public class Solution {
public ListNode combineLists(ListNode oddListHead, ListNode revEvenListHead)
{
ListNode oddTempNode=oddListHead;
ListNode evenTempNode=revEvenListHead;
ListNode result= new ListNode(-1);
ListNode tempNode=result;
while(oddTempNode!=null && evenTempNode!=null)
{
nextOddNode=oddTempNode.next;
nextEvenNode=evenTempNode.next;
tempNode.next=oddTempNode;
tempNode=tempNode.next;
tempNode.next=evenTempNode;
tempNode=tempNode.next;
oddTempNode=nextOddNode;
evenTempNode=nextEvenNode;
}
return result.next;
}
public ListNode reverseList(ListNode head){
ListNode prev=null;
ListNode curr=head;
while(curr!=null)
{
ListNode NEXT = curr.next;
curr.next=prev;
prev=curr;
curr=NEXT;
if(NEXT!=null)
{
NEXT=NEXT.next;
}
}
return prev;
}
public int getLinkedListSize(ListNode head)
{
int count=0;
ListNode tempNode=head;
while(tempNode!=null)
{
tempNode=tempNode.next;
count++;
}
return count;
}
public ListNode evenReverse(ListNode head) {
//You can code here
if(getLinkedListSize(head)<=3){
return head;
}
ListNode tempNode=head;
ListNode oddListHead= new ListNode(head.val);
ListNode evenListHead= new ListNode(head.next.val);
ListNode oddPtr=oddListHead;
ListNode evenPtr=evenListHead;
int count=1;
while(tempNode!=null){
ListNode newNode= new ListNode(tempNode.val);
if(count%2!=0)
{
oddPtr.next=newNode;
oddPtr=oddPtr.next;
}
else{
evenPtr.next=newNode;
evenPtr=evenPtr.next;
}
tempNode=tempNode.next;
}
ListNode revEvenListHead=reverseList(evenListHead);
return combineLists(oddListHead,revEvenListHead);
}
}Editor is loading...
Leave a Comment