Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Reverse Linked List in Pairs

Medium Acceptance 63.00% Points 30.00

You are given the head of a singly linked list. Your task is to reverse every two consecutive nodes in the linked list and return the head of the modified list. If the linked list contains an odd number of nodes, the last node remains unchanged.

Examples
Example 1

Example 1

Input: head = [1,2,3,4,5,6]

Output: [2,1,4,3,6,5]

Explanation: Each pair of adjacent nodes is reversed.

Example 2

Example 2

Input: head = [1,2,3,4,5]

Output: [2,1,4,3,5]

Explanation: The last node has no pair, so it remains unchanged.

Example 3

Example 3

Input: head = [10]

Output: [10]

Explanation: A single-node linked list remains unchanged.

Hints
Hint 1
N/A
Constraints
  • 1 = Number of nodes = 105
  • -10? = Node.data = 10?
Companies
Amazon Microsoft Apple Samsung Visa
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions