C语言单链表怎么插入节点

C语言单链表怎么插入节点,第1张

#include "sll_node.h"  

#include <stdlib.h>  

  

#define FALSE   0  

#define TRUE    1  

  

// insertNode2:把newValue的值插入到递增排序的链表中,正确返回TRUE,错误返回FALSE  

// nextp是指向当前节点指针,最初是头指针  

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  

}

单链表 *** 作很简单的,

插入 *** 作如下:

1.

创建一个新节点并分配空间

pt

2.

移动到要插入的节点

p1

3.

新节点->next=p1->next

将新节点指向当前的节点的下一个节点

4.

p1->next=pt

将当前节点指向新节点

加分了

#include<stdio.h>

#include<stdlib.h>

class point //节点类

{

public:

int a //节点值

point *next//next指针

}

void newlast(point *&p,int i) //在*p所指的链表的最后新建一个值为i的节点

{

point *q,*o

q=p

while(q->next)

{

q=q->next

}

printf("%d\n",q->a)

o=(point *)malloc(sizeof(point))

o->a=i

q->next=o

o->next=NULL //结束标记

}

void show(point *p)//输出指针p所指链表

{

point *q

q=p

while(q)

{

printf("%d\t",q->a)

q=q->next

}

printf("\n")

}

int main()

{

point b1,b2,b3

point *p

b1.a=1

b2.a=2

b3.a=3

p=&b1

b1.next=&b2

b2.next=&b3

b3.next=NULL //结束标记

show(p)

newlast(p,4)

show(p)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11621652.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存