1、题目:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
2、解答:题目的意思是 两两交换结点,最后返回头结点。,这类题,主要搞清楚链表的指向问题,也是递归问题。
3、C++代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dumy = new ListNode(0);
ListNode *p = head ,*q = nullptr;
ListNode *prev = dumy;
dumy->next = head;
while(p && p->next){ //prev 为先前结点,p为当前结点,q为当前结点的下一个结点。
q = p->next;
prev->next = q;
p->next = q->next;
q->next = p;
prev = p;
p = p->next;
}
return dumy->next;
}
};
python代码
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dumy = ListNode(0)
prev = dumy
dumy.next = head
p = head
while p and p.next:
q = p.next
prev.next = q
p.next = q.next
q.next = p
prev = p
p = p.next
return dumy.next