zoukankan      html  css  js  c++  java
  • leetcode链表--18、remove-nth-node-from-end-of-list(从链表中删除倒数第k个结点)

    题目描述
     
    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.
     
    解题思路:参照找倒数第k个结点那个题
    1)两个指针p1 p2  p2先走k-1,然后两个指针一起走,p2走到最后,p1即为倒数第k个结点pre为倒数第k+1个结点
    2)从链表中删除第k个节点
    本题应注意边界条件的判断:
    1)链表为空
    2)要删除的正好是第一个结点的情况
     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         if(head == NULL)
    13             return NULL;
    14         ListNode *pPre = NULL;
    15         ListNode *p1 = head;
    16         ListNode *p2 = head;
    17         for(int i=0;i<n-1;i++)
    18         {
    19             p2 = p2->next;
    20         }
    21         while(p2->next != NULL)
    22         {
    23             pPre = p1;
    24             p1 = p1->next;
    25             p2 = p2->next;
    26         }
    27         if (pPre == NULL)//正好要删除的就是第一个结点
    28         {
    29             head = p1->next;
    30             delete p1;
    31         }
    32         else
    33         {
    34            pPre->next = p1->next;
    35            delete p1;
    36         }
    37  
    38         return head;
    39     }
    40 };
  • 相关阅读:
    html5-特殊符号的使用
    html5-表格
    html5-列表
    html5-绝对路径/相对路径
    html5-嵌入图片
    html5-超级链接
    html5-常用的文本元素
    html5-了解元素的属性
    Scanner类throwFor(Unknown Source)及跳过下一个扫描器分析
    有关HashMap的一些问题及解答
  • 原文地址:https://www.cnblogs.com/qqky/p/6919866.html
Copyright © 2011-2022 走看看