zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】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.
    

    Note:
    Given n will always be valid.
    Try to do this in one pass.

    普通青年解法:

    设置三个指针ABC,指针A和B间隔n-1个结点,B在前A在后,用指针A去遍历链表直到指向最后一个元素,则此时指针B指向的结点为要删除的结点,指针C指向指针B的pre,方便删除的操作。

    代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *removeNthFromEnd(ListNode *head, int n) {
    12         ListNode *target = head;
    13         ListNode *target_pre = NULL;
    14         ListNode *findthelast = head;
    15         
    16         if (head == NULL)
    17             return head;
    18         
    19         while(--n>0)
    20             findthelast = findthelast->next;
    21         
    22         while (findthelast->next) {
    23             target_pre = target;
    24             target = target->next;
    25             findthelast = findthelast->next;
    26         }
    27         
    28         if (target_pre == NULL) {
    29             head = target->next;
    30             return head;
    31         }
    32         
    33         target_pre->next = target->next;
    34         
    35         return head;
    36     }
    37 };

    文艺智慧青年解法:

     (需要更多理解)

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

    附录:

    C++二重指针深入

  • 相关阅读:
    【大数据】中文词频统计
    【大数据】复合数据类型,英文词频统计
    Hadoop综合大作业
    分布式文件系统HDFS练习
    安装关系型数据库MySQL 安装大数据处理框架Hadoop
    爬取全部的校园新闻
    作业六|获取一篇新闻的全部信息
    理解爬虫原理
    作业——04 中文词频统计
    复合数据类型,英文词频统计
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4145709.html
Copyright © 2011-2022 走看看