#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *pNext;
}Node, *PNODE, *List;
PNODE CreateNode(int data)
{
PNODE pNew = (Node *)malloc(sizeof(Node));
pNew->data = data;
pNew->pNext = NULL;
return pNew;
}
List CreateList(int src[], int length)
{
int i = 0;
PNODE pHead = CreateNode(-1);
PNODE p = pHead;
for (i=0; i<length;i++)
{
PNODE pNew = CreateNode(src[i]);
p->pNext = pNew;
p = p->pNext;
}
return pHead;
}
void Append(List pHead, int val)
{
PNODE p = pHead;
while (p->pNext)
{
p = p->pNext;
}
p->pNext = CreateNode(val);
}
int Insert(List pHead, int pos, int val)
{
int i;
PNODE p;
PNODE pNew;
if (pHead == NULL || pos < 1)
return -1;
p = pHead;
for (i=1; i< pos; i++)
{
if (p == NULL)
{
return -1;
}
p = p->pNext;
}
pNew = CreateNode(val);
pNew->pNext = p->pNext;
p->pNext = pNew;
return 0;
}
int Delete(List pHead, int data)
{
PNODE pPrev;
PNODE pCurr;
if (pHead == NULL || pHead->pNext == NULL)
return -1;
if (pHead->data == data)
{
Node *p = pHead;
pHead = pHead->pNext;
free(p);
p = NULL;
}
pPrev = pHead;
pCurr = pHead->pNext;
while (pCurr != NULL)
{
if (pCurr->data == data)
{
pPrev->pNext = pCurr->pNext;
free(pCurr);
pCurr = NULL;
return 0;
}
pPrev = pCurr;
pCurr = pCurr->pNext;
}
return -1;
}
void Print(List pHead)
{
PNODE p;
if (pHead == NULL)
{
return;
}
p = pHead->pNext;
while (p != NULL)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
void main()
{
int temp[] = { 7,1,3,9,6,4,3,6,2 };
List pHead = CreateList(temp, sizeof(temp) / sizeof(int));
Print(pHead);
Insert(pHead, 1, 10);
Insert(pHead, 8, 0);
Print(pHead);
Append(pHead,11);
Print(pHead);
Delete(pHead, 9);
Delete(pHead, 1);
Delete(pHead, 11);
Print(pHead);
system("pause");
}
数据结构和算法【C语言】---单链表
最新推荐文章于 2024-04-12 17:33:25 发布