一系列链表题
1、鏈表的倒序輸出:(輸出4,3,2,1)在這里,可以使用遞歸的方式:
<span style="font-size:18px;">void Reverse(pNode pHead) {if(pHead){Reverse(pHead->next);cout<<pHead->data<<"->"; } } </span> 2、刪除無(wú)頭單鏈表的非尾節(jié)點(diǎn)(不能遍歷)思路:目前只給出了刪除的位置,既然不能遍歷,我們就無(wú)法知道刪除元素節(jié)點(diǎn)的前一個(gè)位置。這時(shí)候我們可以從它的后一個(gè)節(jié)點(diǎn)入手,可以刪除后一個(gè)節(jié)點(diǎn),然后將后一個(gè)元素的值保留,賦給前一個(gè)節(jié)點(diǎn)的值。
如圖:
實(shí)現(xiàn)代碼:
<span style="font-size:18px;">void DeleteListNotTail(pNode *pHead,pNode pos) {assert(pHead);if(*pHead == NULL || pos->next == NULL)return;pNode pDel = pos->next;pos->next = pDel->next;pos->data = pDel->data;free(pDel); }</span> 3、在無(wú)頭單鏈表的非頭節(jié)點(diǎn)處插入一個(gè)節(jié)點(diǎn)(不能遍歷)思路:可以在位置之后插入一個(gè)節(jié)點(diǎn),然后交換兩個(gè)節(jié)點(diǎn)的值。
實(shí)現(xiàn)代碼:
<span style="font-size:18px;">void InsertNotHead(pNode *pHead,pNode pos,DataType data) {if(*pHead == NULL || pos == *pHead)return;pNode newNode = BuyNode(pos->data);newNode->next = pos->next;pos->next = newNode;pos->data = data; }</span>4、查找單鏈表的中間節(jié)點(diǎn)
思路:可以定義快慢兩個(gè)指針,一個(gè)走一步,一個(gè)走兩步。當(dāng)快指針到達(dá)終點(diǎn)時(shí),慢指針就在中間位置。
在這里,還得分為奇數(shù)個(gè)節(jié)點(diǎn)和偶數(shù)個(gè)節(jié)點(diǎn)。(偶數(shù)個(gè)節(jié)點(diǎn)有兩個(gè)中間節(jié)點(diǎn)哦)
關(guān)于偶數(shù)個(gè)節(jié)點(diǎn),我們?cè)摲祷啬囊粋€(gè)呢,如果返回3,就讓pFast指向NULL,如果返回2,就讓pFast->next指向NULL;
如果兩個(gè)都返回的話(huà),就要用一個(gè)結(jié)構(gòu)體來(lái)接收哦。
實(shí)現(xiàn)代碼:
<span style="font-size:18px;">pNode FindMidNode(pNode pHead) {assert(pHead);pNode pFast = pHead;pNode pSlow = pHead;//while(pFast && pFast->next) //偶數(shù)個(gè)節(jié)點(diǎn)時(shí),中間節(jié)點(diǎn)返回后一個(gè)//{// pFast = pFast->next->next;// pSlow = pSlow->next;//}while(pFast->next && pFast->next->next) //偶數(shù)個(gè)節(jié)點(diǎn)時(shí),中間節(jié)點(diǎn)返回前一個(gè){pFast = pFast->next->next;pSlow = pSlow->next;}return pSlow; }</span>5、查找倒數(shù)第K個(gè)節(jié)點(diǎn)(只能遍歷一次)
思路:用快慢兩個(gè)指針,先讓快指針先走K步,然后快慢指針一起向前走。當(dāng)快指針指向NULL的時(shí)候,慢指針就指向倒數(shù)第K個(gè)節(jié)點(diǎn)。
這里強(qiáng)調(diào)的是走K步和走K-1步。(一個(gè)是后置--,一個(gè)是前置--,二者是不一樣的)
<span style="font-size:18px;">pNode FindLastK(pNode pHead,int k) {assert(pHead);int count = k;pNode pFast = pHead;pNode pSlow = pHead;if(pHead == NULL || k <= 0) //邊界條件判斷return NULL;/*while(count--) //pFast移動(dòng)k次{if(pFast == NULL)return NULL;pFast = pFast->next; }while(pFast){pFast = pFast->next;pSlow = pSlow->next;}*/while(--count) //pFast移動(dòng)k-1次{if(pFast == NULL)return NULL;pFast = pFast->next; }while(pFast->next){pFast = pFast->next;pSlow = pSlow->next;}return pSlow; } </span>6、單鏈表的逆置/反轉(zhuǎn)
思路:用三個(gè)指針互相轉(zhuǎn)換,用2->1,然后再整體向后移動(dòng)。直到所有的都鏈起來(lái)。
實(shí)現(xiàn)代碼:
pNode ReverseList(pNode pHead) //逆置 {assert(pHead);if(pHead == NULL || pHead->next == NULL)return pHead;pNode pPre = pHead;pNode pCur = pPre->next;pNode pNext = pCur->next;while(pNext){pCur->next = pPre;pPre = pCur;pCur = pNext;pNext = pNext->next;}pCur->next = pPre;pHead->next = NULL;return pCur; }
之后遇到其他鏈表題的話(huà)還會(huì)繼續(xù)補(bǔ)充哦。
總結(jié)
- 上一篇: 成都大熊猫繁育基地门票优惠
- 下一篇: 静态多态之泛型编程(模板)