题解 | #找出单向链表中的一个节点到尾指针的距离为K#
找出单向链表中的一个节点,该节点到尾指针的距离为K
https://www.nowcoder.com/practice/0cff324157a24a7a8de3da7934458e34
#include <iostream> using namespace std; struct ListNode { int m_nKey; ListNode* m_pNext; }; ListNode *head,*r,*p,*d; int pos; int main() { cin >>pos; head = new ListNode; head->m_nKey = 1; head->m_pNext = NULL; r=head; //链表初始化 for(int i=2 ; i<=7 ;i++) { p = new ListNode; p->m_nKey = i; p->m_pNext = NULL; r->m_pNext = p; r=p; } //输出链表,检查赋值是否正确 // r=head; // while(r->m_pNext != NULL) // { // cout << r->m_nKey <<" "; // r=r->m_pNext; // } // cout << r->m_nKey; r=head; p = r->m_pNext; d = p->m_pNext; while(true) { p->m_pNext = r; if (d->m_pNext !=NULL) {r = p ; p = d; d = d->m_pNext;} else {d->m_pNext = p; break;} } head = d; //最后一个指针为头指针 r=head; for(int i=1;i<=pos-1;i++) { r = r->m_pNext; } cout << r->m_nKey; return 0; } // 64 位输出请用 printf("%lld")