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; }