Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
There is no trick for this problem. Just do it carefully.
C++ Code:
/* * func: swap_pairs * goal: swap every two adjacent nodes and return its head * @param head: head node of the list * return: new head of the list */ ListNode* swap_pairs(ListNode *head){ //If it is a null list or there is only one node in the list, return if(head == nullptr || head->next == nullptr){ return head; } ListNode* new_head = head->next; ListNode* current = head; ListNode* previous = nullptr; while(current != nullptr && current->next != nullptr){ //Store next node needed to be swaped ListNode *next = current->next->next; //Link the previous one to the current one's next if(previous != nullptr){ previous->next = current->next; } //Make current one's next linked to current one current->next->next = current; //Make current one linked to the next node current->next = next; //Continue to the next pair previous = current; current = current->next; } return new_head; }
Python Code:
# func: swap every two adjacent nodes in a linked list # @param head: head node of the linked list # @return: new head def swap_pairs(head): if not head or not head.next: return head else: new_head = head.next current = head previous = None while current and current.next: next = current.next.next if previous: previous.next = current.next current.next.next = current current.next = next previous = current current = current.next return new_head
No comments:
Post a Comment