求:node
给定一个链表,删除链表的倒数第 n 个节点,而且返回链表的头结点。spa
示例:rem
给定一个链表: 1->2->3->4->5, 和 n = 2.List
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:进阶
给定的 n 保证是有效的。链表
进阶:next
你能尝试使用一趟扫描实现吗?di
解:while
struct
ListNode* removeNthFromEnd(
struct
ListNode* head,
int
n){
int
nodeCount =
0
;
int
i;
struct
ListNode* p = head;
struct
ListNode* tmp;
while
(p!=NULL){
nodeCount++;
p=p->next;
}
p=head;
if
(n==nodeCount){
tmp = head;
head = head->next;
free(tmp);
}
else
{
for
(i=
0
;i<nodeCount-n-
1
;i++){
p=p->next;
}
tmp = p->next;
p->next=tmp->next;
free(tmp);
}
return
head;
}
解:
struct
ListNode* removeNthFromEnd(
struct
ListNode* head,
int
n){
struct
ListNode* p1=(
struct
ListNode*)malloc(
sizeof
(
struct
ListNode));
struct
ListNode* p2=(
struct
ListNode*)malloc(
sizeof
(
struct
ListNode));
struct
ListNode* result = p1;
p1->next = head;
p2->next = head;
int
i;
for
(i=
0
;i<n;i++){
p2=p2->next;
}
while
(p2->next!=NULL){
p2=p2->next;
p1=p1->next;
}
struct
ListNode* tmp = p1->next;
p1->next=tmp->next;
free(tmp);
return
result->next;
}