單向連結串列的C實現
阿新 • • 發佈:2018-12-15
單向連結串列:
/*結構體定義*/
#define ERROR -1
#define OK 0
typedef int DataType
typedef struct Node
{
DataType data;
struct Node* next;
}Node,*PNODE;
/*初始化連結串列*/
void initList(PNODE *pHead)
{
if (NULL == p_Head)
return;
*pHead = NULL;
}
PNODE newNode(DataType vData) { PNODE newNode = NULL; newNode = (PNODE)malloc(sizeof(Node)); if (NULL == newNode) { return ERROR; } else { newNode->data = vData; newNode->next = NULL; } return newNode; }
void popBack(PNODE *pHead)//尾刪 { if (NULL == pHead) return; if (NULL == *pHead) return; if (NULL == (*pHead)->next)//只有頭結點,刪除頭結點,釋放記憶體 { PNODE tempnode = *pHead; free(tempnode); tempnode = NULL; *pHead = NULL; } else { PNODE curNode = *pHead; while(curNode->next->next) { curNode = curNode->next; } curNode->next = NULL; } }
void pushBack(PNODE *pHead, DataType vData)//尾插
{
if (NULL == pHead)
return;
if (NULL == *pHead)
{
*pHead = newNode(vData);
}
else
{
PNODE curNode = *pHead;
while(curNode->next->next)
{
curNode = curNode->next;
}
curNode->next = newNode(vData);
}
}
void popFront(PNODE *pHead)//頭刪 { if (NULL == pHead) return; if (NULL == *pHead) { return; } else if(NULL == (*pHead)->next) { *pHead = NULL; } else { PNODE preNode = *pHead; pHead = preNode->next; free(preNode); preNode = NULL; } }
void pushFront(PNODE *pHead, DataType vData)//頭插
{
PNODE preNode = NULL;
PNODE tempNode = NULL;
if (NULL == pHead)
return;
tempNode = newNode(vData);
preNode = *pHead;
tempNode->next = preNode;
*pHead = tempNode;
}
void insertList(PNODE pos, DataType vData)//data 後插入節點pos
{
PNODE preNode = NULL;
PNODE tempNode = NULL;
if (NULL == pos)
return;
preNode = pos;
tempNode = newNode(vData);
tempNode->next = preNode->next;
preNode->next = tempNode;
}