LeetCode 19 寻找倒数第n个数

LeetCode 19 Medium(寻找单链表倒数第N个数)

解题思路:
  • 设置两个指针 pNode和lNode ,并且设置头节点headPoint方便删除第一个元素的统一处理
  • 在current_i < n之前,让lNode移动
  • 当lNode抵达n时,再让pNode移动,最终pNode移动length-n个位置,最终停留在倒数第n个元素上
  • 同时设置pre指针,指向pNode的前一个元素
  • 对边界进行处理,如果head == NULL 则直接返回NULL(好像c语言不能这么做),如果head->next = = NULL ,则返回NULL(因为题目要求n是一定合法的)
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
结果:

在这里插入图片描述

代码:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* headpoint = (ListNode *)malloc(sizeof(ListNode));
        headpoint->next = head;
        if(head==NULL){return head;}
        if(head->next == NULL){
            head = NULL;
            return head;
        }
        int current_i=0,current_n=0;
        ListNode* pNode = headpoint;
        ListNode* lNode = headpoint;
        ListNode* pre = headpoint;
        while(lNode != NULL){
            if(current_i>=n){
                current_n ++;
                pre = pNode;
                pNode = pNode->next;
            }
            current_i ++;
            lNode = lNode->next;
        }
        pre->next = pNode->next;
        return headpoint->next;
    }
};
发布了17 篇原创文章 · 获赞 0 · 访问量 467

猜你喜欢

转载自blog.csdn.net/chizhonghang/article/details/103901909