链表其他操作
每K个节点旋转一次
https://blog.csdn.net/w5761499123/article/details/61616910
给一个链表,两两交换其中的节点,然后返回交换后的链表。
样例
给出 1->2->3->4, 你应该返回的链表是 2->1->4->3。
解题
递归方式
交换p 和 p.next 结点
swapHead = p.next
swapHead.next = p
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
// Write your code here
ListNode p = head;
if(p==null || p.next==null)
return p;
ListNode pNextNext = p.next.next;
ListNode swapHead = p.next; // 交换p 和 p.next 两个结点
swapHead.next = p; // 进行交换
ListNode swapNextNext = swapPairs(pNextNext); // 递归
p.next = swapNextNext;
return swapHead;
}
}
循环方式
参考链接
加上头结点,利用头结点进行交换
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null && head.next.next != null) {
ListNode n1 = head.next, n2 = head.next.next;
// head->n1->n2->...
// => head->n2->n1->...
head.next = n2;
n1.next = n2.next;
n2.next = n1;
// move to next pair
head = n1;
}
return dummy.next;
}
}
更改值的方式进行交换
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
// Write your code here
ListNode p = head;
if(p==null || p.next==null)
return p;
while(p != null && p.next != null){
int val = p.val;
p.val = p.next.val;
p.next.val = val;
p = p.next.next;
}
return head;
}
}