主頁 > 企業開發 > 在C中洗掉雙向鏈表中的唯一元素

在C中洗掉雙向鏈表中的唯一元素

2022-11-14 02:52:29 企業開發

我需要一些幫助來洗掉 C 中雙向鏈表中的唯一字符。所以這是我嘗試實作的邏輯:我計算了雙向鏈表中每個字符的出現次數。如果它的出現是1次,那么它是唯一的元素,需要洗掉。我將對所有元素重復該程序。但是我在 remove_unique_dll() 函式中的代碼不能正常作業,請幫我修復它。這是我的代碼-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
    char data;
    struct node *next;
    struct node *prev;
};

struct node *head, *tail = NULL; //Represent the head and tail of the doubly linked list  
int len;

void addNode(char data)
{
    struct node *newNode = (struct node*) malloc(sizeof(struct node)); //Create new node  
    newNode->data = data;

    if (head == NULL)
    {      //If dll is empty  
        head = tail = newNode;  //Both head and tail will point to newNode  
        head->prev = NULL; //head's previous will point to NULL  
        tail->next = NULL; //tail's next will point to NULL, as it is the last node of the list  
    }
    else
    {
        tail->next = newNode; //newNode will be added after tail such that tail's next points to newNode  
        newNode->prev = tail; //newNode's previous will point to tail  
        tail = newNode;  //newNode will become new tail  
        tail->next = NULL; //As it is last node, tail's next will point to NULL  
    }
}

void remove_unique_dll()
{
    struct node *current = head;
    struct node *next;
    struct node *prev;
    int cnt;

    while (current != NULL)
    {
        next = current->next;
        cnt = 1;

        //printf("!%c ",next->data);

        while (next != NULL)
        {
            if (next->data == current->data)
            {
                cnt  = 1;
                next = next->next;
            }
            else
                next = next->next;

            //printf("@%c %d %c\n",next->data,cnt,current->data);
        }

        if (cnt == 1)
        {
            prev = current->prev;
            //printf("@%c %d",prev->data,cnt);

            if (prev == NULL)
            {
                head = next;
            }
            else
            {
                prev->next = next;
            }

            if (next == NULL)
            {
                tail = prev;
            }
            else
            {
                next->prev = prev;
            }

        }
        current = current->next;
        //printf("#%c ",current->data);
    }

    head = current;
}

void display()
{
    struct node *current = head;  //head the global one

    while (current != NULL)
    {
        printf("%c<->", current->data); //Prints each node by incrementing pointer.  
        current = current->next;
    }

    printf("NULL\n");
}

int main()
{
    char s[100];
    int i;

    printf("Enter string: ");
    scanf("%s", s);

    len = strlen(s);
    for (i = 0; i < len; i  )
    {
        addNode(s[i]);
    }

    printf("Doubly linked list: \n");
    display();

    remove_unique_dll();

    printf("Doubly linked list after removing unique elements: \n");
    display();

    return 0;
}

輸出是這樣的- 在C中洗掉雙向鏈表中的唯一元素

如果您取消注釋 remove_unique_dll() 中的 printf() 陳述句,您會注意到內部 while 回圈結束后沒有執行內部 while 回圈下面的代碼。這里有什么問題,解決方案是什么?

樣本輸入 - aacb

預期輸出 - a<->a<->NULL

uj5u.com熱心網友回復:

一些問題:

  • 你不應該head = current在最后分配,因為那時currentNULL

  • 您在洗掉部分使用的next不是 的后繼current,所以這會產生錯誤的鏈接

  • 當您在串列中前進時,每個值都會在某個時候被視為唯一的:當它是最后一次出現時,您將不再找到重復項,因為您的邏輯只向前看,而不是向后看。

  • 當你洗掉一個節點時,你應該釋放它的記憶體。

  • 不是一個大問題,但沒有理由真正計算重復的數量。一旦找到第一個副本,就沒有理由再尋找另一個了。

您應該真正將演算法的不同步驟隔離在單獨的函式中,這樣您就可以分別除錯和測驗每個功能,并更好地理解您的代碼。

此外,要檢查重復項,您可能需要使用以下事實:如果串列中第一次出現的值與該值最后一次出現的節點相同,那么您知道它是唯一的。由于您的串列是雙重鏈接的,因此您可以使用向后遍歷來查找最后一次出現(并使用前向遍歷來查找第一次出現)。

這是一些建議的代碼:

struct node* findFirstNode(char data) {
    struct node *current = head;
    while (current != NULL && current->data != data) {
        current = current->next;
    }
    return current;
}

struct node* findLastNode(char data) {
    struct node *current = tail;
    while (current != NULL && current->data != data) {
        current = current->prev;
    }
    return current;
}

void removeNode(struct node *current) {
    if (current->prev == NULL) {
        head = current->next;
    } else {
        current->prev->next = current->next;
    }
    if (current->next == NULL) {
        tail = current->prev;
    } else {
        current->next->prev = current->prev;
    }
    free(current);
}

void remove_unique_dll() {  
    struct node *current = head;
    struct node *next;

    while (current != NULL)
    {
        next = current->next;
        if (findFirstNode(current->data) == findLastNode(current->data)) {
            removeNode(current);
        }
        current = next;
    }
}

uj5u.com熱心網友回復:

你至少有三個錯誤。

在計算一個專案的出現次數后,您可以next在幾個地方使用。但是,next已用于遍歷串列。它被移到最后,現在是一個空指標。您可以使用 重置它,next = current->next;也可以將使用的位置更改nextcurrent->next

最后remove_unique_dll,你有head=current;. 目前沒有理由更新head每當從串列中洗掉第一個節點時,remove_unique_dll更新head. 所以它已經更新了。洗掉該行head=current;

這將留下代碼,洗掉每個專案只出現一次。但是,根據您的示例輸出,您希望保留多次出現的專案。為此,您需要重新考慮remove_unique_dll決定洗掉哪些節點的邏輯。當它看到第一個a時,它會掃描串列的其余部分并看到第二個,因此它不會洗掉第一個a當它看到第二個a時,它會掃描串列的其余部分并且沒有看到重復項,因此它會洗掉第二個a你需要改變它。

uj5u.com熱心網友回復:

讓我們逐步考慮您的代碼。

您似乎認為在此宣告中

struct node *head, *tail = NULL; //Represent the head and tail of the doubly linked list  

兩個指標headtail都由 顯式初始化NULL實際上只有指標tail被顯式初始化NULLhead僅由于將宣告置于檔案范圍內,該指標被隱式初始化為空指標。它將這樣的宣告放在塊范圍內,然后指標head將被取消初始化。

相反,你應該寫

struct node *head = NULL, *tail = NULL; //Represent the head and tail of the doubly linked list  

當函式依賴于這些全域變數時,這也是一種非常糟糕的方法。在這種情況下,您將無法在一個程式中擁有多個串列。

還有len僅在 main 中用作全域變數的變數的宣告

int len;

也是個壞主意。而且這個宣告是多余的。

您需要再定義一個結構,該結構將包含指標headtail作為資料成員,例如

struct list
{
    struct node *head;
    struct node *tail;
};

addNode當無法分配新節點時,該函式可以呼叫未定義的行為

void addNode(char data)
{
    struct node *newNode = (struct node*) malloc(sizeof(struct node)); //Create new node  
    //...

您應該檢查一個節點是否分配成功,只有在這種情況下才更改其資料成員。并且您應該報告呼叫者是否創建了節點。

所以該函式應該回傳一個整數,它將報告成功或失敗。

remove_unique_dll在這個while回圈之后的函式中

    while (next != NULL)
    {
        if (next->data == current->data)
        {
            cnt  = 1;
            next = next->next;
        }
        else
            next = next->next;

        //printf("@%c %d %c\n",next->data,cnt,current->data);
    }

如果cnt等于1

    if (cnt == 1)
    //..

那么指標next等于NULLnext然后使用指標

        if (prev == NULL)
        {
            head = next;
        }
        else
        {
            prev->next = next;
        }

是錯的。

您還需要檢查是否存在與當前節點的值相同的前一個節點。否則,您可以洗掉不是唯一的節點,因為在它之后沒有具有相同值的節點。

而這個說法

head = current;

沒有意義,因為在外部 while 回圈之后

while (current != NULL)

指標current等于NULL

請注意,如果該函式將回傳已洗掉的唯一元素的數量,則該函式對用戶更有用。

這是一個演示程式,展示了如何remove_unique_dll定義串列和函式。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
    char data;
    struct node *next;
    struct node *prev;
};

struct list
{
    struct node *head;
    struct node *tail;
};

int addNode( struct list *list, char data )
{
    struct node *node = malloc( sizeof( *node ) );
    int success = node != NULL;

    if (success)
    {
        node->data = data;
        node->next = NULL;
        node->prev = list->tail;

        if (list->head == NULL)
        {
            list->head = node;
        }
        else
        {
            list->tail->next = node;
        }

        list->tail = node;
    }

    return success;
}

size_t remove_unique_dll( struct list *list )
{
    size_t removed = 0;

    for ( struct node *current = list->head; current != NULL; )
    {
        struct node *prev = current->prev;

        while (prev != NULL && prev->data != current->data)
        {
            prev = prev->prev;
        }

        if (prev == NULL)
        {
            //  there is no preceding node with the same value
            //  so the current node is possibly unique

            struct node *next = current->next;
            while (next != NULL && next->data != current->data)
            {
                next = next->next;
            }

            if (next == NULL)
            {
                // the current node is indeed unique

                struct node *to_delete = current;
                if (current->prev != NULL)
                {
                    current->prev->next = current->next;
                }
                else
                {
                    list->head = current->next;
                }

                if (current->next != NULL)
                {
                    current->next->prev = current->prev;
                }
                else
                {
                    list->tail = current->prev;
                }

                current = current->next;

                free( to_delete );

                  removed;
            }
            else
            {
                current = current->next;
            }
        }
        else
        {
            current = current->next;
        }
    }

    return removed;
}

void display( const struct list *list )
{
    for (const node *current = list->head; current != NULL; current = current->next)
    {
        printf( "%c<->", current->data );
    }

    puts( "null" );
}

int main()
{
    struct list list = { .head = NULL, .tail = NULL };

    const char *s = "aabc";

    for (const char *p = s; *p != '\0';   p)
    {
        addNode( &list,  *p );
    }

    printf( "Doubly linked list:\n" );
    display( &list );

    size_t removed = remove_unique_dll( &list );

    printf( "There are removed %zu unique value(s) in the list.\n", removed );

    printf( "Doubly linked list after removing unique elements:\n" );
    display( &list );
}

程式輸出為

Doubly linked list:
a<->a<->b<->c<->null
There are removed 2 unique value(s) in the list.
Doubly linked list after removing unique elements:
a<->a<->null

當不再需要串列時,您至少需要再撰寫一個函式來釋放所有分配的記憶體。

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532305.html

標籤:C指针数据结构双向链表

上一篇:通過顯式算術計算元素指標是否有效?

下一篇:Go:如何將float32指標轉換為float64指標

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more