题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
思路:
a,b两个节点交换的时候需要记录a的前一个节点的指针和b的后一个节点的指针,所以交换节点的方法传当前节点作为参数,交换当前节点的后两个节点。
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode ans = new ListNode(0);
ans.next = head;
ListNode cur = ans;
while(cur != null){
swapNext(cur);
if(cur.next == null)
break;
cur = cur.next.next;
}
return ans.next;
}
private void swapNext(ListNode cur){
//0->1->2->3
if(cur == null || cur.next == null)
return;
ListNode next = cur.next;//1
if(next.next != null){
ListNode nextNext = next.next;//2
ListNode nextNextNext = nextNext.next;//3
if(nextNext != null){
cur.next = nextNext;//0->2
nextNext.next = next;//2->1
next.next = nextNextNext;//1->3
}
}
}
}
网友评论