c语言链表插入节点函数 c语言链表节点是什么( 二 )


printf("要创建一个链表吗?");
scanf(" %c", c);
while (c == 'y' || c == 'Y')
{
head = add(head);
printf("要继续创建节点吗?");
scanf(" %c", c);
}
display(head);
int b;
printf("输入插入的数据");
scanf("%d", b);
head = insert(head, b);
display(head);
freeNode(head);
}
struct link *add(struct link *head)
{
int data;
struct link *p = (struct link*)malloc(sizeof(struct link));
if (head == NULL)
{
head = p;
}
else
{
struct link *pr = head;//一个临时指针pr先保存下head的地址
while (pr-next != NULL)
{
pr = pr-next;
}
pr-next = p;
}
printf("输入数据");
scanf("%d", p-data);
p-next = NULL;
return head;
}
void display(struct link *head)
{
struct link *pr = head;
while (pr != NULL)
{
printf("%d\n", pr-data);
pr = pr-next;
}
}
struct link *insert(struct link *head, int b)
{
struct link *ptr = head, *prev = head;
struct link *newNode = (struct link *)malloc(sizeof(struct link));
newNode-data = https://www.04ip.com/post/b;
while (ptrbptr-data) {
prev = ptr;
ptr = ptr-next;
}
newNode-next = ptr;
if (ptr == head) head = newNode;
else prev-next = newNode;
return head;
}
void freeNode(struct link *node) {
if (!node) return;
freeNode(node-next);
free(node);
}
你好,请问一下怎么用C语言编写单链表插入节点程序,万分感谢!#include "sll_node.h"
#include stdlib.h
#define FALSE0
#define TRUE1
// insertNode2:把newValuec语言链表插入节点函数的值插入到递增排序的链表中c语言链表插入节点函数,正确返回TRUEc语言链表插入节点函数,错误返回FALSE
// nextp是指向当前节点的指针,最初是头指针
int insertNode2(Node **nextp, int newValue)
{
Node *newNode; // 新节点指针
Node *current; // 当前节点指针
current = *nextp; // 最初当前节点为nextp指针指向的节点
// 查找新插入节点的位置
while (current != NULLcurrent-valuenewValue)
{
nextp = ¤t-next;
current = current-next;
}
// 为新节点分配内存
newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL)
return FALSE;
newNode-value = https://www.04ip.com/post/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; i5; 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;
}
C语言单链表怎么插入节点#include "sll_node.h"
#include stdlib.h
#define FALSE0
#define TRUE1
// insertNode2:把newValue的值插入到递增排序的链表中 , 正确返回TRUE,错误返回FALSE
// nextp是指向当前节点的指针,最初是头指针
int insertNode2(Node **nextp, int newValue)
{
Node *newNode; // 新节点指针

推荐阅读