版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/84842520
题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题
- 设置两个指针, 当前节点cur和下一个节点next, 每次交换cur和next即可 :
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummyHead = new ListNode(0);
ListNode pre = dummyHead;
// 每次cur和next交换位置
ListNode cur = head;
ListNode next = head.next;
while (cur != null && next != null) {
// 交换cur 和next
cur.next = next.next;
next.next = cur;
pre.next = next;
// 移动pre, cur, next
pre = cur;
cur = cur.next;
if (cur == null){
break;
}
next = cur.next;
}
return dummyHead.next;
}
}