Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2:
Input: head = [] Output: []
Example 3:
Input: head = [1] Output: [1]
Constraints:
- The number of nodes in the list is in the range
[0, 100]
. 0 <= Node.val <= 100
解法一
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
递归的方法,每次的方法中只需要调转当前的两个节点~
解法二
def swapPairs(self, head: ListNode) -> ListNode:
if(head is None or head.next is None):
return head
T=ListNode(1)
l=T
q=head
h=head.next
head=h
while(True):
q.next=h.next
h.next=q
l.next=h
l=q
if(q.next):
q=q.next
else:
break
if(q.next):
h=q.next
else:
break
return head
我自己的方法就比较啰嗦了