#include <iostream>
using namespace std;
typedef struct ListNode* List;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};
ListNode* createList(int N)
{
int n;
ListNode *front,*rear;
rear = new ListNode(0);//指针的末尾结点
front = rear;//头结点
while (N--)
{
cin >> n;
ListNode *p = new ListNode(0);
p->val = n;
rear->next = p;
rear = p;
}
return front->next;
}
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode* dummyHead = new ListNode(0);//申请头结点
dummyHead->next = head;
ListNode *p1, *p2;
p1 = dummyHead;
p2 = dummyHead;
for (int i = 0; i < n+1; i++)
{
p1 = p1->next;
}
while (p1)
{
p2 = p2->next;
p1 = p1->next;
}
ListNode* tmp;
tmp = p2->next;
p2->next = tmp->next;
delete tmp;
ListNode *retNode = dummyHead->next;
return retNode;
}
void print(List L)
{
while (L)
{
cout << L->val<<" ";
L = L->next;
}
cout << endl;
}
int main()
{
ListNode *L1,*L2;
L1=createList(5);
print(L1);
L2=removeNthFromEnd(L1, 2);
print(L2);
return 0;
}
力扣——19删除倒数第n个结点
最新推荐文章于 2023-04-25 16:46:26 发布