java - How to reverse a linked list at an assigned index? -
this question has answer here:
- issues reversing objects in linkedlist 2 answers
public void reverse(int index) { if (first == null) { return; } int count = 0; node current = first; node previous = null; node next; while (current != null && count < index && index> 0) { next = current.next; current.next = previous; previous = current; current = next; count++; } first = previous; } here code. want reverse linked list , stop reverse process @ index. example, suppose have {one 2 3 4 five}, , index 3. output {three 2 1 4 five}. code, able reverse data before given index, reason, output becomes {three 2 one}. how keep rest of data while reversing @ given index?
from post @ issues reversing objects in linkedlist
if pass index greater number of elements in list, reverses entire list. if pass 0 or 1, list unaffected
public boolean reversetillindex(int index) { int count = 0; if (index == 0) { return false; } node endcountnode = head; while (count++ < index && endcountnode != null) { endcountnode = endcountnode.next; } count = 0; // standard reverse list code node current = head; node h2 = null; while (current != null && count++ < index) { head = current.next; current.next = h2; h2 = current; current = head; } head = h2; while (h2.next != null) { h2 = h2.next; } h2.next = endcountnode; return true; }
Comments
Post a Comment