Doubly Linked List: Swap First and Last Node Values
📌 Problem Statement
Given a doubly linked list, implement a method called swapFirstLast() that swaps the values of the first and last nodes without modifying the structure of the list.
If the length of the list is less than 2, the method should not perform any operation.
Function Signature
public void swapFirstLast();
Input
- The method is part of a DoublyLinkedList class.
- The class has:
- head pointer (points to the first node).
- tail pointer (points to the last node).
- length attribute (stores the number of nodes in the list).
- The list may be empty, contain only one node, or have two or more nodes.
Output
- The method does not return any value.
- It modifies the doubly linked list in-place by swapping the values of the first and last nodes.
- The node structure (pointers) must remain unchanged.
Constraints
✅ 0 ≤ length ≤ 10⁵
✅ The doubly linked list supports operations such as getHead(), getTail(), append(), and printList().
✅ The method must run in O(1) time complexity.
✅ Only the values should be swapped, not the nodes themselves.
1. I made a mistake in the first place because I didn't read the instructions thoroughly.
So, I tried to switch the nodes instead of ju st swapping their values.
public void swapFirstLast() {
if (length >= 2) {
Node n = head.next;
Node p = tail.prev;
tail.next = n;
tail.prev = null;
p.next = head;
head.prev = p;
head.next = null;
n.prev = tail;
Node prev = head;
head = tail;
tail = prev;
}
}
2. The instructions say that only the values should be swapped, not the nodes.|
public void swapFirstLast() {
if (length < 2) return; //Swapping is only possible if there are at least two nodes
int temp = head.value;
head.value = tail.value;
tail.value = temp;
}
'Data Structures & Algorithms' 카테고리의 다른 글
HT: Finding Common Elements (0) | 2025.02.25 |
---|---|
Stack: Parentheses Balanced (0) | 2025.02.23 |
Stack: Reverse a String (0) | 2025.02.22 |
LL: Find K-th Node From End (0) | 2025.02.21 |
Floyd’s Cycle Finding Algorithm (0) | 2025.02.21 |