24. Swap Nodes in Pairs
题目
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, you should return the list as2->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 | class Solution { |
思路
指针的赋值操作中,左边指的是某个域,右边指的是某个位置.
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找到对应的节点.
Author: corn1ng
Link: https://corn1ng.github.io/2018/01/20/算法/leetcode24/
License: 知识共享署名-非商业性使用 4.0 国际许可协议