Java Exercises: Swap every two adjacent nodes of a given linked list
Java Basic: Exercise-180 with Solution
Write a Java program to swap every two adjacent nodes of a given linked list.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
ListNode l = new ListNode(10);
l.next = new ListNode(20);
l.next.next = new ListNode(30);
l.next.next.next = new ListNode(40);
l.next.next.next.next = new ListNode(50);
System.out.println("\nOriginal Linked list:");
printList(l);
ListNode p = swap_Pairs(l);
System.out.println("\n\nAfter swiping Linked list becomes:");
printList(p);
}
public static ListNode swap_Pairs(ListNode head) {
ListNode temp = new ListNode(0);
temp.next = head;
head = temp;
while (head.next != null && head.next.next != null) {
ListNode a = head.next;
ListNode b = head.next.next;
head.next = b;
a.next = b.next;
b.next = a;
head = a;
}
return temp.next;
}
static void printList(ListNode p) {
while (p != null) {
System.out.print(p.val);
if (p.next != null) {
System.out.print("->");
}
p = p.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
Sample Output:
Original Linked list: 10->20->30->40->50 After swiping Linked list becomes: 20->10->40->30->50
Flowchart:
Java Code Editor:
Company: Uber Microsoft Bloomberg
Contribute your code and comments through Disqus.
Previous: Write a Java program to plus one to the number of a given positive numbers represented as an array of digits.
Next: Write a Java program to find the length of last word of a given string. The string contains upper/lower-case alphabets and empty space characters ' '.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework