[关闭]
@XQF 2018-03-07T22:50:45.000000Z 字数 1227 阅读 984

如何删除链表倒数第K个元素

数据结构与算法


快慢指针,有点变化的是这个k是从0还是从1开始,这样的变化在快指针进行计数的时候有变化。
结束的还是根据快指针的next来判断。

1.首发

  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. public ListNode(int val) {
  5. this.val = val;
  6. }
  7. }
  8. public class Solution {
  9. //k为倒数
  10. public ListNode remove(ListNode list, int k) {
  11. ListNode head = list;
  12. ListNode fast = head;
  13. ListNode slow = head;
  14. int counter = 0;
  15. while (fast != null) {
  16. if (counter == k + 1) {//这里
  17. break;
  18. }
  19. counter++;
  20. fast = fast.next;
  21. }
  22. while (slow != null) {
  23. if (fast.next == null) {
  24. slow.next = slow.next.next;
  25. break;
  26. }
  27. fast = fast.next;
  28. slow = slow.next;
  29. }
  30. return head;
  31. }
  32. public void print(ListNode head) {
  33. while (head != null) {
  34. System.out.print(" " + head.val);
  35. head = head.next;
  36. }
  37. }
  38. public ListNode getListNode() {
  39. ListNode head = null;
  40. ListNode p = null;
  41. for (int i = 0; i < 10; i++) {
  42. ListNode node = new ListNode(i);
  43. if (head == null) {
  44. head = node;
  45. p = head;
  46. } else {
  47. p.next = node;
  48. p = p.next;
  49. }
  50. }
  51. return head;
  52. }
  53. public static void main(String[] args) {
  54. ListNode head;
  55. Solution solution = new Solution();
  56. head = solution.getListNode();
  57. solution.print(head);
  58. solution.remove(head, 2);
  59. System.out.println();
  60. solution.print(head);
  61. }
  62. }

2.重构

  1. public ListNode remove(ListNode list, int k) {
  2. ListNode head = list;
  3. ListNode fast = head;
  4. ListNode slow = head;
  5. for (int i = 0; i < k+1; i++) {
  6. fast = fast.next;
  7. }
  8. while (fast.next != null) {
  9. fast = fast.next;
  10. slow = slow.next;
  11. }
  12. slow.next = slow.next.next;
  13. return slow;
  14. }

总结,这个移动指定数值个点还是用能控制次数的循环比较快。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注