@XQF
2018-03-07T22:50:45.000000Z
字数 1227
阅读 984
数据结构与算法
快慢指针,有点变化的是这个k是从0还是从1开始,这样的变化在快指针进行计数的时候有变化。
结束的还是根据快指针的next来判断。
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class Solution {
//k为倒数
public ListNode remove(ListNode list, int k) {
ListNode head = list;
ListNode fast = head;
ListNode slow = head;
int counter = 0;
while (fast != null) {
if (counter == k + 1) {//这里
break;
}
counter++;
fast = fast.next;
}
while (slow != null) {
if (fast.next == null) {
slow.next = slow.next.next;
break;
}
fast = fast.next;
slow = slow.next;
}
return head;
}
public void print(ListNode head) {
while (head != null) {
System.out.print(" " + head.val);
head = head.next;
}
}
public ListNode getListNode() {
ListNode head = null;
ListNode p = null;
for (int i = 0; i < 10; i++) {
ListNode node = new ListNode(i);
if (head == null) {
head = node;
p = head;
} else {
p.next = node;
p = p.next;
}
}
return head;
}
public static void main(String[] args) {
ListNode head;
Solution solution = new Solution();
head = solution.getListNode();
solution.print(head);
solution.remove(head, 2);
System.out.println();
solution.print(head);
}
}
public ListNode remove(ListNode list, int k) {
ListNode head = list;
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k+1; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return slow;
}
总结,这个移动指定数值个点还是用能控制次数的循环比较快。