This is my method to swap two adjacent elements by adjusting only the links (and
ID: 3843988 • Letter: T
Question
This is my method to swap two adjacent elements by adjusting only the links (and not the data) using a single linked list. But when I run the test program it is printing the list without the swap. I know I am not accessing the linked list when i swap so I am not sure what the test program code should look like in order for the swap to work.
Notes: beforep is an input parameter that represents the node before the two adjacent nodes that are to be swapped.
public class Problem1Swapping {
public static void swapWithNext(Node beforeP) {
Node p; //First Node to be swapped
Node afterP;//Second Node to be swapped
p = beforeP.next;
afterP = p.next;
p.next = afterP.next;
beforeP.next = afterP;
afterP.next = p;
}
}
//Provided Node class to use for problem 1
public class Node {
public Object data;
public Node next;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
@Override
public String toString(){
return this.data + "";
}
}
public class Problem1SwappingTester {
public static void main(String args[]){
Node node1 = new Node(25, null);
Node node2 = new Node(35, node1);
Node node3 = new Node(46, node2);
Node node4 = new Node(57, node3);
Node node5 = new Node(68, node4);
LinkedList list1 = new LinkedList();
list1.add(node5);
list1.add(node4);
list1.add(node3);
list1.add(node2);
list1.add(node1);
System.out.println(list1);
Problem1Swapping.swapWithNext(node3);
System.out.println(list1);
}
}
OUTPUT:
run:
[68, 57, 46, 35, 25]
[68, 57, 46, 35, 25]
BUILD SUCCESSFUL (total time: 0 seconds)
Explanation / Answer
Here, declared swap function with head node as parameter
void SwapWithNext(struct node *head)
{
struct node *t = head;
while (t != NULL && t->next != NULL)
{
/* Swap data of node with its next node's data */
swap(&t->data, &t->next->data);
t = t->next->next;
}
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.