自定義實現的帶頭結點的鏈表

//鏈表實現
#include <stdio.h>
#include <stdlib.h>


//鏈表結構體
typedef int datatype;
typedef struct NODE
{
datatype data;
struct NODE *next;
}Node;
typedef struct LIST
{
Node *phead;
int length;
}List;
//創建空鏈表
List *CreateList()
{
Node *phead=(Node *)malloc(sizeof(Node));
phead->next=NULL;
if(NULL==phead)
{
return NULL;
}
List *list=(List *)malloc(sizeof(List));
if(NULL==list)
{
return NULL;
}
list->phead=phead;
list->length=0;

return list;
}
//獲取鏈表的長度
int GetLength(List *pList)
{
return list->length;
}
bool DeleteNewNode(Node *newnode)
{
if(newNode==NULL)
{
return false;
}
Node *ptr=newNode->next;
while(ptr)
{
newNode->next=ptr->next;
delete ptr;
newNode=newNode->next;
}
return true;
}
bool DestoryList(List *pList)
{
Node *ptr=pList->phead;
if(DeleteNewNode(ptr))
{
free(ptr);
ptr=NULL;
return true;
}

}
//添加一個節點
List *InsertNode(List *pList,int pos,datatype data)
{
if(pos<1 || pos>GetLength(pList))
{
printf("the postion is invaliadate\n");
return NULL; 
}
else
{
Node *newNode=(Node *)malloc(sizeof(Node));
newNode->data=data;
if(pos==1)
{
if(plist->phead->next==NULL)
{
Node *pTemp=pList->phead;
pTemp->next=newNode;
newNode->next=NULL;
}
else
{
Node *pTemp=pList->phead;
newNode->next=pTemp->next;
pTemp->next=newNode;
}

}
else if(pos==GetLength(plist))
{
Node *pTail=plist->phead;
while(pTail->next)
{
pTail=pTail->next;
}
newNode->next=pTail->next;
pTail->next=newNode;
newNode->next=NULL;
}
else
{
Node *ptr=plist->phead;
for(int i=1;i<pos;++i)
{
ptr=ptr->next;
}
newNode->next=ptr->next;
ptr->next=newNode;
}
++plist->length;
}
return plist;
}
//刪除一個節點
List *DeleteNode(List *pList,int pos,datatype &data)
{
if(pos<1 || pos>GetLength(plist))
{
return NULL;
}
else
{
if(pos==1)
{
Node *ptr=pList->phead;
Node *qtr=plist->phead->next;
if(ptr->next==NULL)
{
ptr->next=qptr->next=NULL;
data=qtr->data;
free(qtr);
}
else
{
ptr->next=qtr->next;
data=qtr->data;
free(qtr);
}

}
else if(pos==GetLength(plist))
{
Node *ptr=plist->phead;
Node *ftr=plist->phead->next;
while(ftr)
{
ftr=ftr->next;
ptr=ptr->next;
}
ptr->next=ftr->next;
data=ftr->data;
free(ftr);
}
else
{
Node *ptr=plist->phead;
for(int i=1;i<pos;++i)
{
ptr=ptr->next;
}
Node *q=ptr->next;
ptr->next=q->next;
data=q->data;
free(ptr);
}
--plist->length;
}
return plist;

}


還需要進行優化處理。。。

發佈了42 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章