• Leetcode | Remove Nth Node From End of List


    Given a linked list, remove the nth node from the end of list and return its head.

    For example,

    Given linked list: 1->2->3->4->5, and n = 2.

    After removing the second node from the end, the linked list becomes 1->2->3->5.

    Method I

    没去想快慢指针的做法。 而是用了一个vector以便可以根据下标定位到具体的节点。

    这里为了删除节点方便,用了指针的指针,ListNode**,这样直接修改当前位置为下一个位置就行了,不管它是不是head。

    注意的是,在循环里面,临时变量p必须也是ListNode**的类型,不能是ListNode*,后者会造成&p得到的是临时地址;

     1 class Solution {
     2 public:
     3     ListNode *removeNthFromEnd(ListNode *head, int n) {
     4         if (head == NULL) return NULL;
     5         vector<ListNode**> nodes;
     6         ListNode** p = &head;
     7         while (*p != NULL) {
     8             nodes.push_back(p);
     9             p = &((*p)->next);
    10         }
    11         *nodes[nodes.size() - n] = (*nodes[nodes.size() - n])->next;
    12         return head;
    13     }
    14 };

    Method II

    用两个指针,第一个指针先跑了n次。然后第二个再跑。这样当第一个指针跑到头时,第二个指针就跑到从后往前数第n个指针了。

     1 class Solution {
     2 public:
     3     ListNode *removeNthFromEnd(ListNode *head, int n) {
     4         if (head == NULL) return NULL;
     5         ListNode** p1 = &head, **p2 = &head;
     6         
     7         for (int i = 0; i < n; ++i) {
     8             if (!*p1) return NULL;
     9             p1 = &((*p1)->next);
    10         }
    11         
    12         while (*p1) {
    13             p2 = &((*p2)->next);
    14             p1 = &((*p1)->next);
    15         }
    16         *p2 = (*p2)->next;
    17         
    18         return head;
    19     }
    20 };

    果然这些链表类的题要一起做,不然都想不到好办法。。。

  • 相关阅读:
    移动端rem布局的适配mixin【转藏】
    移动端布局Demo展示图文
    百思不得其解—这些年做Web开发遇到的坑?
    elemetnui 分页..解决 bug
    linq.js
    yalinqo 的使用...
    vue 利用 v-model 实现 双向传递数据..
    Mui 选项卡 tab 高度 没有自适应....
    css flex 使内容 水平居中 的方法...
    IDEA 在 专注模式下 显示 行号 和 缩进线...
  • 原文地址:https://www.cnblogs.com/linyx/p/3731246.html
Copyright © 2020-2023  润新知