簡體   English   中英

c語言中的單向鏈表

[英]Singly linked list in c

下面是我在 c 中的單鏈表代碼。 誰能幫我這個?

這是我的主要 c 文件:

#include <stdio.h>
#include <stdlib.h>
#include "myclib.c"


struct mydata
{
    int num;
    char name;
    struct mydata *next;
};

int main()
{
    struct mydata *head, *newnode, *temp;

    head = (struct mydata*)malloc(sizeof(struct mydata));
    newnode = (struct mydata*)malloc(sizeof(struct mydata));
    temp = (struct mydata*)malloc(sizeof(struct mydata));

    head -> num = 123;
    head -> name = 'k';
    head -> next = NULL;

    newnode -> num = 456;
    newnode -> name = 'd';
    newnode -> next = NULL;

    printf("before.app.head = %p\n",head);
    printf("before.app.newnode = %p\n",newnode);
    printf("before.app.head->next = %p\n",head -> next);    
    printf("before.app.newnode->next = %p\n",newnode -> next);

    head = (struct mydata*)addNodeAtHead(head, newnode, (newnode -> next));

    printf("after.app.head = %p\n",head);
    printf("after.app.newnode = %p\n",newnode);
    printf("after.app.head->next = %p\n",head -> next); 
    printf("after.app.node->next = %p\n",newnode -> next);

    temp = head;

    while(temp != NULL)
    {
        printf("num : %d\n",temp -> num);
        printf("name : %c\n",temp -> name);
        temp = temp -> next;
    }

    free(temp);
    free(head);

    return 0;
}

這是 myclib.c 文件:

#include <stdio.h>


    void * addNodeAtHead(void *head, void *node, void *nodenext)
    {
        printf("\nbefore.head = %p\n",head);
        printf("before.node = %p\n",node);
        printf("before.nodenext = %p\n",nodenext);
        nodenext = head;
        head = node;
        printf("after.head = %p\n",head);
        printf("after.node = %p\n",node);
        printf("after.nodenext = %p\n\n",nodenext);

        return head;

    }

我正在嘗試在 head 前面添加 newnode,而不是將 head 指針更改為 newnode。

當您將(newnode -> next)傳遞給函數addNodeAtHead (newnode -> next)被復制到函數中的node變量中。 並且您正在使用新值head更新該node變量。 函數執行后node變量被銷毀並且與(newnode -> next)沒有關系。 因此(newnode -> next)保持不變。

addNodeAtHead它,只需像下面這樣更改您的addNodeAtHead

void * addNodeAtHead(void *head, void *node)
{
    printf("\nbefore.head = %p\n",head);
    printf("before.node = %p\n",node);
    ((mydata *)node)-> next = (mydata *) head;
    printf("after.head = %p\n",head);
    printf("after.node = %p\n",node);

    return node;

}

並簡單地稱之為:

  head = (struct mydata*)addNodeAtHead(head, newnode);

現在一切都應該好了。

#include <stdio.h>
#include <stdlib.h>
//#include "myclib.c"

struct mydata
{
    int num;
    char name;
    struct mydata *next;
};

struct mydata* addNodeAtHead(struct mydata* head, struct mydata* node)
{
#ifdef DEBUG
    printf("\nbefore.head = %p\n",head);
    printf("before.node = %p\n",node);
//  printf("before.nodenext = %p\n",nodenext);
#endif
    if(node){
        node->next = head;
        head = node;
    }
#ifdef DEBUG
    printf("after.head = %p\n",head);
    printf("after.node = %p\n",node);
//  printf("after.nodenext = %p\n\n",nodenext);
#endif

    return head;

}

int main()
{
    struct mydata *head, *newnode, *temp;

    head = (struct mydata*)malloc(sizeof(struct mydata));
    newnode = (struct mydata*)malloc(sizeof(struct mydata));
    //temp = (struct mydata*)malloc(sizeof(struct mydata));//unused and rewrite to other pointer

    head -> num = 123;
    head -> name = 'k';
    head -> next = NULL;

    newnode -> num = 456;
    newnode -> name = 'd';
    newnode -> next = NULL;

#ifdef DEBUG
    printf("before.app.head = %p\n",head);
    printf("before.app.newnode = %p\n",newnode);
    printf("before.app.head->next = %p\n",head -> next);    
    printf("before.app.newnode->next = %p\n",newnode -> next);
#endif

    head = (struct mydata*)addNodeAtHead(head, newnode);

#ifdef DEBUG
    printf("after.app.head = %p\n",head);
    printf("after.app.newnode = %p\n",newnode);
    printf("after.app.head->next = %p\n",head -> next); 
    printf("after.app.node->next = %p\n",newnode -> next);
#endif

    temp = head;

    while(temp != NULL)
    {
        printf("num : %d\n",temp -> num);
        printf("name : %c\n",temp -> name);
        temp = temp -> next;
    }
/*
    free(temp);//NULL
    free(newnode);//...
    free(head);//already changed
*/
    temp=head;
    while(temp != NULL){
        struct mydata *prev = temp;
        temp=temp->next;
        free(prev);
    }
    return 0;
}

您需要在添加的節點上設置next指針指向原始頭節點。 我更改了 addNodeAtHead 的簽名:當您始終傳遞 mydata * 類型的指針時,您不應傳遞 void *。 我還將變量名稱更改為更清楚(IMO)其目的

mydata * addNodeAtHead(mydata * original_head, mydata * new_node)
{
    new_node -> next = original_head;
    return new_node; // new_node is now the head of the list!
}
//------ SINGLY LINKED LIST PROGRAM ( CREATION AND TRAVERSING ) -------X 
#include<stdio.h>
#include<conio.h>
struct node
{
  int info;
  struct node *link;
};
struct node *first;
int main()
{
  void create();
  void traverse();
  create();
  traverse();
  return 0;
}
void create()
{
  struct node *cpt,*ptr;
  char ch;
  ptr=(struct node*)malloc(sizeof(struct node));
  printf("enter the data \n");
  scanf("%d",&ptr->info);
  first=ptr;
  do
  {
    cpt=(struct node*)malloc(sizeof(struct node));
    printf("enter the data \n");
    scanf("%d",&cpt->info);
    ptr->link=cpt;
    ptr=cpt;
    printf("Do you want to create a new node <Y/N> :\n");
    ch=getch();
  }
  while(ch=='y');
  ptr->link=NULL;
}
void traverse()
{
  struct node *ptr;
  ptr=first;
  while(ptr!=NULL)
  {
    printf("The entered nodes are:%d \n",ptr->info);
    ptr=ptr->link;
  }
}
**PROGRAM ON SINGLY LINKER LIST ( CREATION AND TRAVERSING WITH COMMENTS )**
#include<stdio.h> //Header file for input and output operations.
#include<conio.h>  
struct node   // structure declaration .
{
int info;            // stores information.
struct node *link;   // stores the address of next link.
};
struct node *first; // used to point to the first node.
void create();      // function call |NOTE| This line is optional.
void traverse();    // function call |NOTE| This line is optional.
int main()          // main function.
{
create();      // function call for creation.
traverse();    // function call for traversing i.e nothing but display.
return 0;
}
void create()      // declaration of create function , creation of nodes.
{
char ch;       // variable to take an input from the user for decision.
struct node *ptr,*cpt; // these are used to create a node and referred to as 
//previous pointer and current pointer.
ptr=(struct node*)malloc(sizeof(struct node)); //dynamic declaration 
printf("Enter data into the first node \n");
scanf("%d",&ptr->info); // taking the input from the user.
first=ptr; //assigning the information taken from previous pointer to first for 
//future identification.
do  // loop which continuously generates and links new nodes to previous nodes.
{
   cpt=(struct node*)malloc(sizeof(struct node)); //dynamic declaration of current 
   //pointer.
   printf("Enter the data for another node \n");
   scanf("%d",&cpt->info); // getting input from the user of next node 
  // information.
   ptr->link=cpt;  // linking the previous pointer to the new pointer.
   ptr=cpt;   // transferring the previous node information to the current node 
   //i.e previous pointer to the current pointer.
   printf("Do you want to create another node <Y/N>:\n\n");
   ch=getch();  // getting the users decision.
   }
   while(ch=='y');  // checking the users decision.
   ptr->link=NULL;  // assigning the previous pointer link to null;
   }
   void traverse()  // function declaration of display or traversing.
   {
   int count=1;   // counting variable for naming the nodes.
   struct node *ptr;   // pointer variable used for traversing.
   ptr=first;  // assigning ptr to the first for starting traversing from the 
   //first node.
   printf("TRAVERSING OF A LINKED LIST \n");
   while(ptr!=NULL)  // checking whether the ptr is null or not, And if not 
   //executes the statements written in the body.
   {
    printf("The data stored in node %d is:%d \n",count,ptr->info);  //prints the 
   // node id and information present in the node.
    ptr=ptr->link;  // This statement is used to traverse to the next node.
    count++;  // count incrementation.
    } 
    }

    // f☺ll☺w ☺n instagram ♥ ---> @cyber_saviour 
#include <stdio.h>

void addNodeAtHead(void **head, void *node){
        void *prH=*head;

        *head=node;
        node->next=prH;
}
#pragma once
#include<iostream>

using namespace std;

class  SKBStringData
{
public:
    SKBStringData();
    ~SKBStringData();

    SKBStringData(const char* iData);

    void SetData(const char* iData);
    char* GetData();

    void SetLink(const SKBStringData* iNext);
    SKBStringData* GetLink();

private:

    char*            _Data;
    SKBStringData*   _Next;
};

#include "SKBStringData.h"

SKBStringData::SKBStringData(void)
{
    _Data = NULL;
    _Next = NULL;
}

SKBStringData::SKBStringData(const char* iData)
{
    _Data =(char*)iData; 
}

SKBStringData::~SKBStringData(void)
{
    _Data = NULL;
    _Next = NULL;
}

void SKBStringData::SetData(const char* iData)
{
    _Data =(char*)iData;    
}

char* SKBStringData::GetData()
{
    return _Data;
}

void SKBStringData::SetLink(const SKBStringData* iNext)
{
    _Next =(SKBStringData*)iNext;
}


SKBStringData* SKBStringData::GetLink()
{
    return _Next;
}


#pragma once
#include<iostream>
#include"SKBStringData.h"

using namespace std;

class  SKBStringList
{
public:

    SKBStringList(void);
    ~SKBStringList(void);


    void SetSize(const int iSize);
    int GetSize();

    void Append(const char* iData); 

    void Remove(const int iPos);    

    int Find(const char* iData);

    void Display();

    void NewListAppend(SKBStringList &iList);

private:

    SKBStringData*          _Head;
    SKBStringData*          _Tail;
    int                     _Size;

};


#pragma once
#include "SKBStringList.h"


SKBStringList::SKBStringList()
{ 
    _Head = NULL;
    _Tail = NULL;
    _Size = 0;
}

SKBStringList::~SKBStringList()
{
    _Head = NULL;
    _Tail = NULL;
}

void SKBStringList::SetSize(const int iSize)
{
    _Size = iSize;
}

int SKBStringList::GetSize()
{
    return _Size;
}

void SKBStringList::Append(const char* iData)
{
    SKBStringData *pNewData = new SKBStringData(iData);

    if(_Head == NULL)
    {
        _Head = pNewData;
        _Tail = pNewData;
        _Size = 1;
    }
    else
    {
        _Tail->SetLink(pNewData);
        _Tail = pNewData;
        _Size++;
    }
    return;
}

void SKBStringList::Remove(const int iPos)  
{
    if(iPos < 0 || _Head == NULL)
    {
        return;
    }

    SKBStringData* pCurrData = _Head;
    SKBStringData* pNextData =  NULL;

    if(iPos == 0)
    {
        _Head = pCurrData->GetLink();
        delete pCurrData;
        _Size = _Size - 1;

        return;
    }

    for(int i = 0; i!=iPos; i++)
    {
        pNextData = pCurrData;
        pCurrData = pCurrData->GetLink();
    }

    pNextData->SetLink(pCurrData->GetLink());
    delete pCurrData;

    _Size = _Size - 1;
    return;
}

int SKBStringList:: Find(const char* iData)
{
    SKBStringData* pCurrData = _Head;

    bool bFound = false;

    int nCount = 0;
    while( pCurrData != NULL)
    {
        if(strcmp(iData,pCurrData->GetData()) == 0)
        {
            bFound = true;
            break;
        }
        nCount = nCount + 1;
        pCurrData = pCurrData->GetLink();
    }

    if( bFound == false)
    {
        return -1;
    }

    return nCount;
}


void SKBStringList::Display()
{
    SKBStringData* pCurrData = _Head;
    int nSize=0;
    if (pCurrData == NULL)
    {
        cout<<"The List is Empty"<<endl;   
        return;
    }

    cout<<"Elements of list are: "<<endl;
    while (pCurrData != NULL)
    {
        cout<<pCurrData->GetData()<<"-> "<<endl;
        pCurrData = pCurrData->GetLink();

        if(pCurrData == _Tail)
        {
            pCurrData->SetLink(NULL);
        }
        nSize++;
    }
    cout<<"Size of list is  ="<<_Size<<endl;
    return;
}

//void SKBStringList::NewListAppend(SKBStringList &iList)
//{
//  SKBStringData *pCurData = _Head;
//  if(pCurData == NULL)
//  {
//      return;
//  }
//
//  int nCount = 0;
//  while(pCurData !=NULL)
//  {
//      SKBStringData *NewNode = new SKBStringData();
//      NewNode->SetData(pCurData->GetData());
//
//      if(strcmp(NewNode->GetData(),pCurData->GetData())==0)
//      {
//          nCount = nCount + 1;
//      }
//
//     // SKBStringData *NewNode = _Head;
//      if(_Head == NULL)
//      {
//          _Head = NewNode;
//          _Tail = NewNode;
//      }
//      else
//      {
//          NewNode->SetLink(NewNode);
//          NewNode = NewNode->GetLink();
//      }
//
//      pCurData = pCurData->GetLink();
//  }
//  return;
//}

//int SKBStringList ::Count()
//{
//  SKBStringData* pCurrData = _Head;                                    // first node of the list
//  SKBStringData* pNextData = pCurrData->GetLink();                    // next node after the head
//
//  int nCount = 0;                                                     
//  while(pCurrData != NULL)
//  {
//      nCount = 1;
//      while(pNextData != NULL)
//      {
//          if(strcmp(pCurrData->GetData(),pNextData->GetData())==0)   // comparing string data 
//          {
//              nCount = nCount + 1;                                   // if two strings found same then count 
//          }
//          pNextData = pNextData->GetLink();                         // traverse to compare head with all other nodes  
//      }
//      pCurrData = pNextData;                                        // assign next data to head 
//      pNextData = pNextData->GetLink();                             // next data will be its next
//      pCurrData = pCurrData->GetLink();                             // traverse 
//  }
//  return nCount;
//}


//int SKBStringList::Count()
//{
//  SKBStringData *pCurData  = _Head;
//  SKBStringData *pNextData = NULL;       //pCurData->SetLink(pCurData->GetLink());
//  SKBStringData *pSaveData = NULL;
//
//  int nCount = 0;
//
//  while (pCurData != NULL && pCurData->GetLink() !=NULL)
//  {
//      //char * pstrCurData=pCurData->GetData();
//      //SKBStringData * pNextData=pCurData->GetLink();
//
//      //char * pstrNextData=pNextData->GetData();
//
//      /*if(strcmp(pstrCurData,pstrNextData)== 0)
//          nCount++;*/
//      pNextData = pCurData;
//
//      while(pNextData->GetLink() != NULL)
//      {
//          if(strcmp(pCurData->GetData(), pNextData->SetLink(pNextData->GetData())== 0)
//      }
//
//
//      pCurData = pCurData->GetLink();
//  }
//  return nCount;
//}

//int SKBStringList ::Count()
//{
//  SKBStringData *pCurData   = _Head;
//  SKBStringData *pNextData  =  pCurData->GetLink() ;                  /*pNextData = pCurData->GetLink();*/
//
//  int nCount = 0;
//  while(pCurData != NULL)
//  {
//    //  pNextData->SetLink(pCurData->GetLink());
//      if(pCurData->GetData() == pNextData->GetData())
//      {
//          nCount= nCount + 1;
//          break;
//      }
//      pCurData = pCurData->GetLink();
//      //pNextData = pCurData->GetLink();
//  }
//  return nCount;
//}


//int SKBStringList ::Count()
//{
//  SKBStringData* pCurrData = _Head;
//  SKBStringData* pNextData = pCurrData->GetLink();
//
//  int nCount = 0;
//  while(pCurrData != NULL && pNextData != NULL)
//  {
//      if(strcmp(pCurrData->GetData(),pNextData->GetData())==0)
//      {
//          nCount = nCount + 1;
//      }
//      pCurrData = pCurrData->GetLink();
//      pCurrData = pNextData;
//      pNextData = pNextData->GetLink();
//  }
//  return nCount;
//}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM