带头链表几种操作的思路和代码

来源:互联网 发布:航天信息a6软件下载 编辑:程序博客网 时间:2024/06/05 14:45
1头插:
定义一该个新结点,将数据给这个结点,再将该结点指向首元结点,再将头头指针指向该节点(新结点变成首元结点)
int Create_List_Head(PNode h, ElementType data)
{
if (h == NULL)
{
return ERROR;
}

PNode node = (PNode)malloc(sizeof(Node)/sizeof(char));//(PNode指针)malloc返回void*万能指针类型
if (node == NULL)
{
return MALLOC_ERROR;
}
node->data = data;
node->next = h->next;
h->next = node;

return OK;
}




2尾插:
首先找到尾结点,定义一个新结点,将数据给新结点,指针域为NULL,将尾结点指向新结点。
int Create_List_Tail(PNode h, ElementType data)
{
if (h == NULL)
{
return ERROR;
}

PNode node = (PNode)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return MALLOC_ERROR;
}
node->data = data;
node->next = NULL;
// 找最后最后一个结点
PNode temp = h;
while (temp->next)
{
temp = temp->next;
}
temp->next = node;

return OK;
}




3在链表中第POS位插入一个值:
首先找到pos的前一个结点(定义为temp),定义一个新结点,给新节点赋值,新结点指向原先pos指的下个结点(temp->next)
,再把新结点与temp连接。


// 在第 pos 个结点处插入一个数据
int Insert_Node(PNode h, int pos, ElementType data)
{
PNode temp = h;
int k=0;

// 找第pos-1个结点
while (temp && k < pos-1)
{
temp=temp->next;
k++;
}

if (temp == NULL && h->next != NULL)  //不是空链表
{
printf ("无效的插入点\n");
return ERROR;
}

PNode node = (PNode)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return MALLOC_ERROR;
}
node->data = data;
node->next = temp->next;
temp->next = node;

return OK;
}




4删除第pos个元素:


一样首先找到第POS位的前一个结点,再将前一个结点指向要删除结点的下个结点,释放第pos结点并置空。


int Delete_Node(PNode h, int pos)
{
PNode temp = h;
int k=0;

// 找要删除的结点的前一个结点,就是temp
while (temp->next && k < pos-1)
{
temp=temp->next;
k++;
}

if (temp->next == NULL && h->next != NULL)
{
printf ("无效的删除点\n");
return ERROR;
}

PNode p = temp->next;
temp->next = p->next;
free(p);
p = NULL;

return OK;
}




5链表逆序
定义两个新结点和一个空结点(用来保存指针)PNode pre = h->next;PNode cur = pre->next;PNode next = NULL;
把链表逆序之前,首先保证链表不会断,next = cur->next(我们要动cur的指针之前先保存它原来的指针方向),
cur->next = pre(开始逆序,cur->next指向前一个结点),pre = cur(cur指向pre);cur = next(next指向car);
最后把头结点和尾结点改下,原先的头结点置为尾结点,原先的尾结点置为头结点。(这种理解方法是只动指针方向
符合链表的特点,还有一种是调换位置,这种理解可能会有点绕。多画图就OK)




int Inverse_List(PNode h)
{
if (h->next == NULL || h->next->next == NULL)
{
return OK;
}

PNode pre = h->next;
PNode cur = pre->next;
PNode next = NULL;

while(cur)
{
next = cur->next;
cur->next = pre;  cur->next指向pre
pre = cur;  //这个地方看指针方向  pre指向car
cur = next;
}

h->next->next = NULL;  ((h->next原来的第一个节点)->next)原来第一个结点指向NULL.
h->next = pre;
return OK;
}
原创粉丝点击