華為機試題 --- 從單向鏈表中刪除指定值的節點


#include <iostream>
using namespace std;
struct ListNode
{
    int  m_nKey;
    ListNode* m_pNext;
};
void insertNode(ListNode* head, int input, int indexVal)
{
    ListNode* curptr = head,*curnext;
    while ( curptr != nullptr && curptr -> m_nKey != indexVal)
    {
        curptr = curptr -> m_pNext;   //指針指向下一個結點
    }            // 經過while后,指針定位到要找的位置處
    ListNode* temptr = new ListNode; //新建一個結點
    temptr -> m_nKey = input;        //存入值到結點
    curnext = curptr -> m_pNext;    
    curptr -> m_pNext = temptr;
    temptr -> m_pNext = curnext;     // 三步完成結點的插入
    
}
void delNode( ListNode* head, int input)
{
    ListNode* curptr = head, *precur;
    if (curptr -> m_nKey == input)     // 頭結點單獨處理
    {
        head = head -> m_pNext;
        delete curptr;
    }
    curptr = head -> m_pNext;
    precur = head;
    while (curptr != nullptr && curptr -> m_nKey != input)
    {      
        curptr = curptr -> m_pNext;   //指針指向下一個結點
        precur = precur -> m_pNext;   
    }  
    precur -> m_pNext = curptr -> m_pNext;
    delete curptr;
}
void disVal( ListNode* head )
{
    ListNode* curptr = head;
    while ( curptr != nullptr )
    {
        cout <<curptr->m_nKey << " ";  // 最后一個數字后邊也有空格,不然過不了
        curptr = curptr -> m_pNext;   //指針指向下一個結點
    }
    cout << endl;     //大坑啊, 加了一句換行就過了
}
int main ()
{
    int num = 0, headVal = 0, delVal = 0;
    int input,indexVal;
    while ( cin >> num )     // 不知道為啥還要循環檢測,真是坑
    {
        cin >> headVal;
        ListNode* head = new ListNode;
        head -> m_nKey = headVal;
        head ->m_pNext = nullptr;
        for ( int i = 0; i < num - 1; i++)
        {
            cin >> input >> indexVal;
            insertNode( head, input, indexVal);
        
        }
        cin >> delVal;
        delNode( head, delVal );
        disVal( head );
    }
    
    return 0;
}

 題目描述 bug太多

題目描述

輸入一個單向鏈表和一個節點的值,從單向鏈表中刪除等於該值的節點,刪除后如果鏈表中無節點則返回空指針。

鏈表結點定義如下:

struct ListNode

{

      int       m_nKey;

      ListNode* m_pNext;

};

詳細描述:

本題為考察鏈表的插入和刪除知識。

鏈表的值不能重復

構造過程,例如

1 -> 2

3 -> 2

5 -> 1

4 -> 5

7 -> 2

最后的鏈表的順序為 2 7 3 1 5 4 

刪除 結點 2 

則結果為 7 3 1 5 4 

 

 


輸入描述:

1 輸入鏈表結點個數
2 輸入頭結點的值
3 按照格式插入各個結點
4 輸入要刪除的結點的值



輸出描述:

輸出刪除結點后的序列


輸入例子:
5
2
3 2
4 3
5 2
1 4
3

輸出例子:
2 1 5 4


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM