Question:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1-> 2-> 3-> 4
, You shoshould return the list2-> 1-> 4-> 3
.
Your algorithm shocould use only constant space. You mayNotModify the values in the list, only nodes itself can be changed.
Resolution: Based on an ordered linked list, swap two adjacent nodes and return the linked list header. Only constant space can be used, and the value inside the node cannot be changed. The main idea is to define two record pointers P1 and P2. P1 indicates the nodes to be processed that are currently traversed in the linked list. P2 indicates the last node in the linked list that has been successfully exchanged.
Note two points: (1) because the linked list may have an even number of nodes or an odd number of nodes, pay special attention to the situation when there are odd numbers of nodes.
(2) Pay attention to the steps before and after the links between the linked list and the deleted links, which are prone to errors.
Java AC code:
Public class solution {public listnode swappairs (listnode head) {If (Head = NULL | head. next = NULL) {return head;} listnode dummy = new listnode (-1); dummy. next = head; listnode p1 = head; listnode P2 = dummy; while (P1! = NULL & p1.next! = NULL) {p2.next = p1.next; p1.next = p1.next. next; p2.next. next = p1; P2 = p2.next. next; P1 = p1.next; If (p1 = NULL) {return dummy. next;} else if (p1.next = NULL) {p2.next = p1; return dummy. next;} return dummy. next ;}}
[Leetcode] swap nodes in pairs