题目地址:
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
给定一个链表,和一个正整数 k k k,要求将该链表的正数第 k k k个和倒数第 k k k个链表节点交换。 k k k从 1 1 1开始计数。
代码如下:
public class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode n1 = head, n2 = head, fast = head;
for (int i = 0; i < k - 1; i++) {
n1 = n1.next;
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
n2 = n2.next;
}
int tmp = n1.val;
n1.val = n2.val;
n2.val = tmp;
return head;
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n), n n n为链表长度,空间 O ( 1 ) O(1) O(1)。