leetcode19 Remove Nth Node From End of List(删除链表的倒数第N个节点)

题目链接
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
知识点:
考察链表、指针相关知识

思路:
1.先遍历一遍计算得到链表的长度,再遍历一遍删除倒数第n个节点
2.双指针法:p指针开始的时候指向虚拟头结点,p、q指针之间的距离一直保持为n,p
、q指针同时往链表尾移动直到q指针指向NULL,代表此时p指针指向的元素就是待删除的元素的前一个元素,再把后面那个元素删除即可.这种方法只遍历一次链表就解决问题了.

下面代码采用思路2的思路.
AC代码:

class Solution
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        assert(n>=0);
        ListNode* dummyhead = new ListNode(0);
        dummyhead->next = head;
        ListNode* p=dummyhead;
        ListNode* q=dummyhead;
        for(int i=0; i<n+1; i++)
        {
            assert(q);
            q=q->next;
        }
        while(q!=NULL)
        {
            p=p->next;
            q=q->next;
        }
        ListNode* delNode = p->next;
        p->next=delNode->next;
        delete delNode;
        ListNode* retNode = dummyhead->next;
        delete dummyhead;
        return retNode;
    }
};

AC代码加测试如下:

#include 
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* createLinkedList(int arr[], int n)
{
    if(n == 0)
        return NULL;
    ListNode* head = new ListNode(arr[0]);
    ListNode* curNode = head;
    for(int i=1; i<n; i++)
    {
        curNode->next = new ListNode(arr[i]);
        curNode = curNode->next;
    }
    return head;
}

void printLinkedList(ListNode* head)
{
    ListNode* curNode = head;
    while(curNode!=NULL)
    {
        cout<<curNode->val<<" -> ";
        curNode = curNode->next;
    }
    cout<<"NULL"<<endl;
}

void deleteLinkedList(ListNode* head)
{
    ListNode* curNode = head;
    while(curNode!=NULL)
    {
        ListNode* delNode = curNode;
        curNode = curNode->next;
        delete delNode;
    }
}

class Solution
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        assert(n>=0);
        ListNode* dummyhead = new ListNode(0);
        dummyhead->next = head;
        ListNode* p=dummyhead;
        ListNode* q=dummyhead;
        for(int i=0; i<n+1; i++)
        {
            assert(q);
            q=q->next;
        }
        while(q!=NULL)
        {
            p=p->next;
            q=q->next;
        }
        ListNode* delNode = p->next;
        p->next=delNode->next;
        delete delNode;
        ListNode* retNode = dummyhead->next;
        delete dummyhead;
        return retNode;
    }
};

int main()
{
    int arr[]= {1,2,3,4,5};
    int n = sizeof(arr)/sizeof(int);
    ListNode* head = createLinkedList(arr,n);
    printLinkedList(head);
    ListNode* head1 = Solution().removeNthFromEnd(head,2);
    printLinkedList(head1);
    deleteLinkedList(head1);
    return 0;
}

leetcode19 Remove Nth Node From End of List(删除链表的倒数第N个节点)_第1张图片

你可能感兴趣的:(链表,leetcode刷题,面试题,笔试题面试题刷题,LeetCode刷题练习,链表,数据结构,C++,leetcode做题代码合集)