1 //单链表反转 2 ListNode* RevertList(ListNode* m_pHead){ 3 ListNode* pCurrent = m_pHead; 4 ListNode* pPrev=NULL; 5 ListNode* pNext =NULL; 6 7 while (pCurrent != NULL) 8 { 9 pNext = pCurrent->m_pNext; 10 pCurrent->m_pNext = pPrev; 11 pPrev = pCurrent; 12 pCurrent = pNext; 13 } 14 return pPrev; 15 }
查找倒数第K个:设置两个指针p1,p2,首先p1和p2都指向链表的头部head,然后p2向前走k步,这样p1和p2之间就间隔k个节点,最后p1和p2同时向前移动,直至p2走到链表末尾,然后返回p1就是我们要找的链表的倒数K个节点。
//查找第倒数第K个 ListNode *theKthofList(ListNode* m_pHead, int k){ ListNode* pBack; ListNode* pPre; pBack= m_pHead; pPre= m_pHead; for (; k>0; k--){ pPre= pPre->m_pNext; //移动pPre到与pBack距离k个位置 } while (pPre!= NULL){ pBack= pBack->m_pNext; //移动p1,pPre直到pPre到达最后 pPre= pPre->m_pNext; } return pBack; }
时间: 2024-11-09 23:45:45