topic:
Give you a linked list,Two or two exchanges are adjacent nodes,And return to the head node of the linked list after exchange。You must complete this question without modifying the internal value of the node(Right now,Can only exchange nodes)。
Exemplary example 1:
enter:head = [1,2,3,4] Output:[2,1,4,3]
Exemplary example 2:
enter:head = [] Output:[]
Exemplary example 3:
enter:head = [1] Output:[1]
hint:
- The number of nodes in the linked list is in the range
[0, 100]
Inside 0 <= Node.val <= 100
24.Two or two exchanges linked watches.md
Thought:
use head 表示原始Linked的头节点,新的Linked的第二个节点,use newHead 表示新的Linked的头节点,原始Linked的第二个节点,则原始Linked中的其余节点的头节点是 newHead.next。make head.next = swapPairs(newHead.next),Indicates two or two exchanges for the rest of the nodes,The new head node after the exchange is head The next node。然后make newHead.next = head,Right now完成了所有节点的交换。最后返回新的Linked的头节点 newHead。
Code:
1 | class Solution: |
1 | class Solution { |