#include <stdlib.h>
#define FALSE 0
#define TRUE 1
// insertNode2:把newValue的值插入到递增排序的链表中,正确返回TRUE,错误返回FALSE
int insertNode2(Node **nextp, int newValue)
{
Node *newNode // 新节点指针
Node *current // 当前节点指针
current = *nextp // 最初当前节点为nextp指针指向的节点
// 查找新插入节点的位置
while (current != NULL && current->value < newValue)
{
nextp = ¤t->next
current = current->next
}
// 为新节点分配内存
newNode = (Node *)malloc(sizeof(Node))
if (newNode == NULL)
return FALSE
newNode->value = newValue
// 统一了插入的步骤。即:每次插入,都是前一个指针指向新节点,新节点指向下一个节点
*nextp = newNode
newNode->next = current
return TRUE
}
main函数
[cpp] view plain copy
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "sll_node.h"
int insertNode(Node **rootp, int newValue)
int insertNode2(Node **nextp, int newValue)
int main()
{
srand(time(0))
Node *head = (Node *)malloc(sizeof(Node))
head->next = NULL
for (int i = 0 i < 5 i++)
{
int temp = rand() % 50
printf("%d\n", temp)
//insertNode(&head,temp)
insertNode2(&head,temp)
}
Node *p = head->next
while (p != NULL)
{
printf("%d\n", p->value)
p = p->next
}
getchar()
getchar()
return 0
}
单向链表的插入图示:---->[NULL](原链表)
head
---->[1]---->[NULL](插入后的链表)
head 1->next
图7 空链表插入一个节点
结合原链表和插入后的链表,就很容易写出相应的代码。 *** 作方法如下:
1、你要明白空链表head指向NULL就是head=NULL;
2、插入后head指向第1个节点,就是让head=1,1->next=NULL,OK这样就行了。
---->[1]---->[2]---->[3]...---->[n]---->[NULL](原链表)
head 1->next 2->next 3->next n->next
---->[1]---->[2]---->[x]---->[3]...---->[n]---->[NULL](插入后的链表)
head 1->next 2->next x->next 3->next n->next
图8:有N个节点的链表,插入一个节点(这里图示插入第2个后面)
结合原链表和插入后的链表,就很容易写出相应的代码。 *** 作方法如下:
1、你要明白原1->next就是节点2,2->next就是节点3;
2、插入后x指向第3个节点,2指向x,就是让x->next=2->next,1->next=x。
*/
struct Node *Insert(struct Node *head, long num, struct Node *node)
{
struct Node *p1 /*p1保存当前需要检查的节点的地址*/
if (head == NULL) /*(结合图示7理解)*/
{
head = node
node->next = NULL
n += 1
return head
}
p1 = head
while (p1->num != num &&p1->next != NULL) /*p1指向的节点不是所要查找的,并且它不是最后一个节点,继续往下找*/
{
p1 = p1->next/*后移一个节点*/
}
if (num == p1->num) /*找到了(结合图示8理解)*/
{
node->next = p1->next/*显然node的下一节点是原p1的next*/
p1->next = node/*插入后,原p1的下一节点就是要插入的node*/
n += 1/*节点总数增加1个*/
}
else
{
printf(" %ld not been found! ",num)
}
return head
}
如果已知一个节点指针pre和一个节点指针cur,要把cur插入到pre节点之后,很显然要保证链表不会断开而丢失后面的节点,要先把后面的节点指针(指向lat的指针)保存下来,即有cur->next = pre->next,然后把cur连接的一串链表连接到pre后面,即pre->next = cur上面介绍了,在一个节点之后插入节点的情况。这是通常的情况。如果要向一个链表的头部插入节点,就只需要将新节点的下一个指针指向链表的头指针即可。
在这种情况下,有两点要注意:
1,链表是否为空链表
2,要插入的节点是不是空指针。
代码实现:
//向单链表中插入一个节点(插入在链开始处)
//输入参数:单链表的头指针和要插入的节点指针
//输出参数:无
//返回值:指向单链表的头指针
SingleList* Insert(SingleList *head,SingleList *node)
{
if(node == NULL)
{
return head
}
else if(head == NULL)
{
return node
}
node->next = head
head = node
return head
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)