学习时间:
2023年1月30日
题目描述:

题解分享:
// 作 者 : 繁 华 倾 夏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> // 调用malloc和free函数
// 力扣(LeetCode):19. 删除链表的倒数第 N 个结点
// Definition for singly-linked list. // 单链表的定义
struct ListNode {
int val;
struct ListNode *next;
};
// head:单链表 n:倒数位
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if (head == NULL) { // 首选需要判NULL
return head;
}
struct ListNode* n1 = head, * n2 = head->next, * n3 = head; // 建立临时指针
int len = 0;
while (n3) { // 遍历n3指针统计len长度
n3 = n3->next;
len++;
}
if (len == n) { // 此处需要判断
if (len == 1) { // 长度相等并且为1时返回NULL
return NULL;
}
else {
head = head->next; // 否则长度相等不为1时返回头结点的下个结点
return head;
}
}
for (int i = 0; i < len - n - 1; i++) { // 遍历单链表
n1 = n1->next; // n1为n2的前一结点
n2 = n2->next; // n2为要删除的结点
}
n1->next = n2->next; // 改变next的指向
free(n2); // free掉要删除的结点
return head; // 返回head链表
}
// 从尾部插入数据
void SListPushBack(struct ListNode** pphead, int x) {
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->val = x;
newnode->next = NULL;
if (*pphead == NULL) {
*pphead = newnode;
}
else {
// 找到尾节点
struct ListNode* tail = *pphead;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newnode;
}
}
// 打印链表
void SListPrint(struct ListNode* phead)
{
struct ListNode* cur = phead;
while (cur != NULL) {
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
// 测试用例
// 输入 head = [1, 2, 3, 4, 5], n = 2
// 输出 [1, 2, 3, 5]
int main() {
struct ListNode* head = NULL; // 建立空链表
SListPushBack(&head, 1); // 为链表插入数据
SListPushBack(&head, 2);
SListPushBack(&head, 3);
SListPushBack(&head, 4);
SListPushBack(&head, 5);
int n = 2;
struct ListNode* re = removeNthFromEnd(head,n);
SListPrint(re);
}
【繁华倾夏】【每日力扣题解分享】【Day16】