单向链表的C实现
程序员文章站
2022-03-11 21:49:36
...
单向链表:
/*结构体定义*/
#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;
}