用C语言写一个简单的循环链表

#include<stdio.h>
#include<stdlib.h>
#include <string.h>

struct node
{
  struct node* p_node;
  int data;
 } ;
typedef  struct node Node;
   
int main()
{

Node* node_temp;//temp的作用主要作为中间元素节点
Node* node_head;//头节点
Node* node_ele;//节点元素

node_temp = (Node *)malloc(sizeof(Node));  
node_head=node_temp;

int i;

for(i=0;i<10;i++)
{	

node_ele = (Node *)malloc(sizeof(Node));  //malloc	

node_ele->data=i;

node_temp->p_node=node_ele;  //temp先作为头节点 ,然后temp指向下一节点 

node_temp=node_ele;  
	
}


node_ele->p_node=node_head->p_node;
node_temp=node_head->p_node;

while(node_temp!=NULL)

{

printf("%d",node_temp->data);
node_temp=node_temp->p_node;

}
}

简单分析一下,如何用for语句快速写一个链表(头插法)。PS:因为总是记不住,so记录一下。

首先,这边主要解释一下node_temp的作用。

1)为node_temp申请内存后,将其作为头节点。node_head=node_temp;

2)  为链表中的元素node_ele申请内存后,在for语句中,依次将node_temp指向前一个node_ele;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
循环双链表插入算法的C语言实现如下: ```c #include <stdio.h> #include <stdlib.h> // 定义双向链表节点结构体 typedef struct Node { int data; struct Node* prev; struct Node* next; } Node; // 定义循环双向链表结构体 typedef struct List { Node* head; Node* tail; } List; // 初始化循环双向链表 void initList(List* list) { list->head = NULL; list->tail = NULL; } // 创建新节点 Node* createNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->prev = NULL; node->next = NULL; return node; } // 在链表尾部插入节点 void insertAtTail(List* list, int data) { Node* node = createNode(data); if (list->head == NULL) { list->head = node; list->tail = node; node->prev = node; node->next = node; } else { node->prev = list->tail; node->next = list->head; list->tail->next = node; list->head->prev = node; list->tail = node; } } // 在链表中间插入节点 void insertAtMiddle(List* list, int data, int position) { Node* node = createNode(data); Node* current = list->head; int i = 1; while (i < position && current != NULL) { current = current->next; i++; } if (current == NULL) { printf("Invalid position\n"); return; } node->prev = current->prev; node->next = current; current->prev->next = node; current->prev = node; } // 打印链表 void printList(List* list) { Node* current = list->head; if (current == NULL) { printf("List is empty\n"); return; } do { printf("%d ", current->data); current = current->next; } while (current != list->head); printf("\n"); } int main() { List list; initList(&list); insertAtTail(&list, 1); insertAtTail(&list, 2); insertAtTail(&list, 3); insertAtTail(&list, 4); insertAtMiddle(&list, 5, 3); printList(&list); return ; } ``` 该算法实现了循环双向链表的初始化、在链表尾部插入节点、在链表中间插入节点和打印链表等功能。其中,insertAtMiddle函数实现了在链表中间插入节点的功能,需要传入链表、要插入的数据和插入的位置三个参数。如果插入位置不合法,会输出"Invalid position"。最后,通过调用printList函数打印链表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值