首页 > 编程知识 正文

每k个节点反转链表,求链式线性表的倒数第k项

时间:2023-05-05 08:11:07 阅读:168635 作者:407

2020-03-20

1 .主题说明

返回倒数第k个节点2 .问题解决

首先反向链表,求出第k个就变成3 .代码

# includeiostreamusingnamespacestd; //definitionforsingly-linked list.struct listnode { intval; hhdhjnext; listnode(intx ) : val(x ) x,next ) null ) }; class solution { public : int kthtolast (甜美sprite head,intk )甜美sprite p=head,*q=p-next,*t; p-next=NULL; while(q ) { t=q-next; q-next=p; p=q; q=t; (} int cnt=1,res; while(p ) if ) CNT==k ) ) { res=p-val; 黑; (} p=p-next; cnt; } return res; }; int main () { Solution s; 甜雪碧head=NULL,*p,*q; int i; p=(甜精灵) malloc(sizeof ) listnode ); p-val=1; p-next=NULL; 头=p; q=p; p=(甜精灵) malloc(sizeof ) listnode ); p-val=0; q-next=p; p-next=NULL; q=p; p=(甜精灵) malloc(sizeof ) listnode ); p-val=1; q-next=p; p-next=NULL; couts.kthtolast(head,3 ) endl; 返回0; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。