题目

  1. 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.

大意

改变相邻两个节点的顺序.

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* prev=dummy;
while(head &&head->next)
{
ListNode* nn=head->next->next;
prev->next=head->next;
head->next->next=head;
head->next=nn;
prev=head;
head=nn;
}
return dummy->next;
}
};

思路

指针的赋值操作中,左边指的是某个域,右边指的是某个位置.

p = q->next; //这里是把q->next指针的值赋予p,即让p指向q->next指向的位置。

q->next = p; //这里把p赋予q->next,即把q的next域指向p指向的位置。

q->next->next =p; //q->next 这个节点的next域指向p指向的位置

等式左边没有next, 就指针跟着动 像上面 1和4 ,左边有next ,最后的一个next是指指针域,前面的next找到对应的节点.