(1)遍历两遍,第一次计算出链表长度n,第二次找到(n-k)个节点,也就是倒数第K个节点。
(2)遍历一遍,定义两个指针,一个指针fast,一个指针slow,都指向头结点,fast指针先向前走K,然后再同时遍历,当fast遍历到最后一个节点时,slow所指向的节点就是倒数第K个节点。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct Listnode
{
int _value;
Listnode* _next;
};
void Init(Listnode*& head)
{
Listnode* cur =head;
if(cur==NULL)
{
cur=(Listnode*)malloc(sizeof(Listnode));
cur->_next=NULL;
cur->_value=0;
}
head=cur;
}
void push(Listnode*& head,int value)
{
Listnode* cur =head;
while(cur->_next)
{
cur=cur->_next;
}
Listnode* tmp=NULL;
tmp=(Listnode*)malloc(sizeof(Listnode));
tmp->_next=NULL;
tmp->_value=value;
cur->_next=tmp;
}
void pop(Listnode* head)
{
Listnode* cur=head;
Listnode* prev=NULL;
while(cur->_next!=NULL)
{
prev=cur;
cur=cur->_next;
}
prev->_next=NULL;
free(cur);
cur=NULL;
}
void print(Listnode* head)
{
Listnode* cur=head;
while(cur)
{
printf("%d\n",cur->_value);
cur=cur->_next;
}
}
Listnode* Find(Listnode* head,int k)
{
assert(head);
assert(k>0);
Listnode* slow=head;
Listnode* fast=head;
while(k--)
{
fast=fast->_next;
}
while(fast)
{
slow=slow->_next;
fast=fast->_next;
}
return slow;
}
void test()
{
Listnode* head=NULL;
Init(head);
push(head,1);
push(head,2);
push(head,3);
/*pop(head);*/
print(head);
Listnode* ret=Find(head,2);
printf("倒数第K个数:%d\n",ret->_value);
}
int main()
{
test();
system("pause");
return 0;
}
结果:
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。