198k views
5 votes
Write a method reverse that reverses the order of the elements in the list. For example, if the variable list initially stores this sequence of integers: [1, 8, 19, 4, 17] It should store the following sequence of integers after reverse is called: [17, 4, 19, 8, 1] Assume that you are adding this method to the LinkedIntList class as defined below: public class LinkedIntList { private ListNode front; // null for an empty list ... }

User Saurin
by
5.9k points

1 Answer

5 votes

Answer:

public reverseListIteratively (Node head)

{

if (head == NULL || head.next == NULL)

return; //empty or just one node in list

Node Second = head.next;

//store third node before we change

Node Third = Second.next;

//Second's next pointer

Second.next = head; //second now points to head

head.next = NULL; //change head pointer to NULL

//only two nodes, which we already reversed

if (Third == NULL)

return;

Node CurrentNode = Third;

Node PreviousNode = Second;

while (CurrentNode != NULL)

{

Node NextNode = CurrentNode.next;

CurrentNode.next = PreviousNode;

/* repeat the process, but have to reset

the PreviousNode and CurrentNode

*/

PreviousNode = CurrentNode;

CurrentNode = NextNode;

}

head = PreviousNode; //reset the head node

}

to swap the list element pairwise

class Node

{

int data;

Node next;

Node(int d) {data = d; next = null; }

}

void pairWiseSwap()

{

Node temp = head;

/* Traverse only till there are atleast 2 nodes left */

while (temp != null && temp.next != null) {

/* Swap the data */

int k = temp.data;

temp.data = temp.next.data;

temp.next.data = k;

temp = temp.next.next;

}

}

Step-by-step explanation:

User Stalinrajindian
by
5.7k points