问题不是太难,但是得注意,移除的第n个结点是从链表结尾算起。
算法思路:
1)首先判断链表head是否为空,或者n是否大于0;
2)统计链表长度length,将从尾部算起待移除的第n个结点转化为从链表首部开始的第target个结点;
(taget=ListLength+1-n)
3) 判断是否删除的是头结点;
4)对链表进行遍历,找到第target结点进行删除;
(添加变量before_head,用于存放当前结点的前个结点地址)
给出算法源码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
int ListLength;
int count=0;
int target;
struct ListNode *c_head=head;
struct ListNode *before_head;
if(n<0 || head==NULL)
{
printf("something wrong in call\n");
exit(-1);
}
//calculate the list length
for( ; c_head!=NULL; c_head=c_head->next)
{
count++;
}
ListLength=count;
c_head=head;
target=ListLength+1-n;
if(target==1)//delete the head
{
head=head->next;
free(c_head);
return head;
}
for(count=0,before_head=c_head; c_head!=NULL; c_head=c_head->next )
{
count++;
if(count==target)
{
before_head->next=c_head->next;
free(c_head);
return head;
}
if(count==1)
{
before_head=before_head;
}
else
{
before_head=before_head->next;
}
}
if(count==ListLength)
{
printf("not found that node\n");
exit(-1);
}
}