题目要求:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
思路:先构造函数遍历链表求出链表的长度,然后再找到要删除结点的前一个结点。如下图一样算出长度length然后用for循环找到要删除结点4的前一个结点3
例如:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ int l(struct ListNode *head) { int i=0; struct ListNode *p; p=head; while(p!=NULL) { p=p->next; i++; } return i; } struct ListNode* removeNthFromEnd(struct ListNode* head, int n){ if(head==NULL) return head; int length; struct ListNode *p=head; length=l(head); if(n==length) return head->next; for(int i=0;i<length-n-1;i++) { p=p->next; } struct ListNode *q=p->next; p->next=q->next; return head; }
运行结果: