Skip to main content

12.2 Basic Operations on Linked Lists

206. Reverse Linked List

Problem Description

Reverse a linked list.

Input and Output Example

Input a linked list, output the reversed linked list.

Input: 1->2->3->4->5->nullptr
Output: 5->4->3->2->1->nullptr

Solution Explanation

Reversing a linked list is a fundamental skill that must be mastered. We provide two approaches—recursive and iterative. It's recommended to learn both.

Recursive Approach:

ListNode* reverseList(ListNode* head, ListNode* head_prev = nullptr) {
if (head == nullptr) {
return head_prev;
}
ListNode* head_next = head->next;
head->next = head_prev;
return reverseList(head_next, head);
}

The non-recursive implementation is as follows:

ListNode* reverseList(ListNode* head) {
ListNode *head_prev = nullptr, *head_next;
while (head) {
head_next = head->next;
head->next = head_prev;
head_prev = head;
head = head_next;
}
return head_prev;
}

21. Merge Two Sorted Lists

Problem Description

Given two sorted linked lists, merge them into one sorted linked list.

Input and Output Example

Input: Two linked lists.
Output: A linked list representing the merged result.

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solution Explanation

We provide both recursive and non-recursive implementations.
The recursive implementation is as follows:

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l2 == nullptr) {
return l1;
}
if (l1 == nullptr) {
return l2;
}
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}

The non-recursive implementation is as follows:

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *dummy = new ListNode(0), *node = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
node->next = l1;
l1 = l1->next;
} else {
node->next = l2;
l2 = l2->next;
}
node = node->next;
}
node->next = l1 == nullptr ? l2 : l1;
return dummy->next;
}

24. Swap Nodes in Pairs

Problem Description

Given a linked list, swap every two adjacent nodes.

Input and Output Example

Input a linked list, output the linked list after swapping nodes in pairs.

Input: 1->2->3->4
Output: 2->1->4->3

Solution Explanation

Use pointers to perform the swap operation. The problem is not very difficult, but requires careful attention.

ListNode* swapPairs(ListNode* head) {
ListNode *node1 = head, *node2;
if (node1 && node1->next) {
node2 = node1->next;
node1->next = node2->next;
node2->next = node1;
head = node2;
while (node1->next && node1->next->next) {
node2 = node1->next->next;
node1->next->next = node2->next;
node2->next = node1->next;
node1->next = node2;
node1 = node2->next;
}
}
return head;
}