zoukankan      html  css  js  c++  java
  • 写一个函数insert,用来向一个动态链表插入结点

    写一个函数insert,用来向一个动态链表插入结点

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct LNode
    {
    	int num;
    	struct LNode *next;
    } LNode;
    
    void insert(int n, LNode *node)
    {
    	//创建新节点
    	LNode *newNode = (LNode *)malloc(sizeof(LNode));
    	newNode->num = n;
    
    	LNode* next = node->next;
    
    	// node ---> newNode  ---> next
    	newNode->next = next;
    	node->next = newNode;
    }
    
    LNode* creat(int n)
    {
    	LNode *head, *p;
    	head = (LNode *)malloc(sizeof(LNode));
    	p = head; //头节点为0 加上头节点共11个节点
    	head->num = 0;
    	head->next = NULL;
    	for (int i = 1; i <= n; i++)
    	{
    		LNode *newNode = (LNode *)malloc(sizeof(LNode));
    		newNode->num = i;
    		newNode->next = NULL;
    		p->next = newNode;
    		p = p->next;
    	}
    	return head;
    }
    
    void printNode(LNode* head)
    {
    	LNode* p = head->next;
    	while (p != NULL)
    	{
    		printf("num -> %d
    ", p->num);
    		p = p->next;
    	}
    }
    
    int main()
    {
    	LNode *head;
    	int n;
    	head = creat(10);
    	printNode(head);
    	printf("请输入需要插入的节点:
    ");
    	scanf("%d", &n);
    	insert(n, head);
    	printf("链表的新内容:
    ");
    	printNode(head);
    	return 0;
    }
    

    运行截图:

    写一个函数insert,用来向一个动态链表插入结点

  • 相关阅读:
    OpenCV笔记——cvFloodFill漫水填充算法
    C# 总结 随笔
    MYSQL存储过程 随笔
    MYSQL总结 随笔
    xPath 总结 随笔
    Javascript 总结 随笔
    linux中top查看cpu使用率超过100%
    页面优化小记1
    基于数据库的多语言解决方案
    基于消息队列的日志组件
  • 原文地址:https://www.cnblogs.com/weiyidedaan/p/13331296.html
Copyright © 2011-2022 走看看