java - How to reverse a linked list at an assigned index? -


this question has answer here:

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

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -