链接:
https://leetcode.com/problems/swap-nodes-in-pairs/
题意:
给定一个链表,交换相邻两个链表节点(0号和1号交换,2号和3号交换),不能使用交换节点值的方法完成
思路:
首先,判断两种边界情况:链表为空或者链表只有一个节点,则直接返回链表即可
根据测试用例解释:(没有用例感觉自己说不清,词穷......)

首先,定义两个变量h,hCur。h为新链表的头节点,hCur为上一轮交换操作后的的到的新链表最后一个节点。则在第一轮交换过程中,只需:先记录head(为节点1)以及next=head.next(为节点2)。然后记录一下t=next.next(为节点3);之后使得
next.next = head; (2指向1)
head.next = null;(1指向null)
hCur.next = next; (上一轮的尾节点指向本次交换后的next节点)
hCur=head;(定义本次交换后得到的尾节点)
head=t;(定义下次交换的第一个节点)
重复过程,直到head==null或者head.next==null;
而当head.next==null时,需要再设置hCur.next=head;(因为之前hCur.next是指向null)
代码:
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode h = new ListNode(0), hCur = h;
while (head != null) {
ListNode next = head.next;
if (next == null) {
hCur.next = head;
break;
}
ListNode t = next.next;
next.next = head;
hCur.next = next;
hCur = head;
hCur.next = null;
head = t;
}
return h.next;
}
}
结果:

结论:
链表题目一般来说还是比较简单的,只要把题目意思理解清楚,节点之间的逻辑关系转换正确就可以
博客围绕LeetCode上交换链表相邻节点的题目展开。介绍题意为在不交换节点值的情况下交换相邻节点。给出思路,先判断边界情况,再通过定义变量记录节点,按特定逻辑交换节点,重复操作直至满足条件。最后指出链表题理解题意、转换逻辑关系很重要。
177

被折叠的 条评论
为什么被折叠?



