题目
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
分析
- 定义虚拟头节点和连个节点指针,通过指针的移动变换实现节点的交换
代码和注释
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode ret, *p, *q; //定义虚拟头节点和两个指针变量
ret.next = head; //虚拟头节点指向真正的头节点
p = &ret; //p指针指向虚拟头节点
q = head; //q指针指向头节点
while(q && q->next) { // 如果一对中的第一个节点为null或者只有第一个头节点,那么不用处理,直接返回就行
p->next = q->next; // 接下来三行就是对相邻的两个节点的位置进行交换
q->next = p->next->next;
p->next->next = q;
p = q; //此时的p相当于下一对节点的虚拟头节点
q = q->next; // q相当于下一对节点的第一个节点
}
return ret.next;
}