背景
链表是一种很基础的数据结构,涉及结构体,指针,动态内存分配,释放,链表遍历,首尾及中间结点的不同处理。熟练掌握链表的增删功能,对于理解C语言的上述概念,显得尤为重要。
有如下题目:
给你一个链表,删除倒数第n个结点,并且返回链表的头结点,最后打印整个链表。
input 1:head=[1,2,3,4,5],n=2,输出[1,2,3,5]
input 2:head=[1],n=1,输出[]
input 3:head=[1,2],n=1,输出[1]
约束:结点个数sz [1,30],结点值Node.val [1,100],n [1,sz]
代码实践:
先贴一张辅助理解链表多结点的插图:
开始代码:
#include <stdio.h>
/*标准输入输出printf*/
#include <string.h>
/*字符串长度strlen*/
#include <stdlib.h>
/*动态内存申请及释放malloc,free*/
/*结点类型定义*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct ListNode* head,int n)
{
struct ListNode *parray[30]={0},*last;
int i=1;/*至少一个结点,用来记录结点总数*/
parray[0]=head;
last=head;
while(last->next)
{
last=last->next;
parray[i]=last;
i++;
}
if (i==1)/*1个结点*/
{
free(head);
return NULL;
} else if (i==2)/*2个结点*/
{
if (n==1)/*删除尾结点*/
{
free(last);
head->next=NULL;
return head;
} else {/*删除首结点*/
free(head);
return last;
}
} else { /*3个及以上结点*/
if (n==1)/*删除尾结点*/
{
free(last);
parray[i-2]->next=NULL;
return head;
} else if (n==i) {/*删除首结点*/
free(head);
return parray[1];
} else {/*删除中间结点*/
free(parray[i-n]);
parray[i-n-1]->next=parray[i-n+1];
return head;
}
}
}
void pushNode(struct ListNode* head,int val)
{
struct ListNode *newNode,*last;
/*找到尾结点*/
last=head;
while(last->next)
{
last=last->next;
}
if ((*head).val == -1) /*首结点未赋值*/
{
(*head).val=val;
} else {
/*新增结点*/
newNode=(struct ListNode*) malloc(sizeof(struct ListNode));
/*结点下个地址指向NULL,截断尾结点*/
newNode->next=NULL;
last->next=newNode;
newNode->val=val;
}
}
void print_node(struct ListNode* head)
{
struct ListNode* last=head;
if (head ==NULL)
{
printf("[]\n");
} else {
printf("[%d",head->val);
while(last->next)
{
last=last->next;
printf(",%d",last->val);
}
printf("]\n");
}
}
int main(void)
{
//char head[30]="[1]";
//char head[30]="[1,2]";
char head[30]="[1,2,3,4,5]";
int n=5;
int len,i;
struct ListNode InitNode={-1,NULL},*headpoint=NULL;
len=strlen(head);
for(i=1;i<len;i=i+2)
{
pushNode(&InitNode,head[i]-'0');
}
headpoint=removeNthFromEnd(&InitNode,n);
printf("input list is %s\n",head);
printf("Delete the last %d node\n",n);
printf("result as follow:\n");
print_node(headpoint);
return 0;
}
测试集及结果: