前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c语言实现的链表

c语言实现的链表

原创
作者头像
东风压倒西风
发布2022-09-28 20:31:29
1.4K0
发布2022-09-28 20:31:29
举报
文章被收录于专栏:卓谷山

C语言实现链表,在数据结构课程中是必须要熟练掌握的。可惜久疏拳法,几乎忘得一干二净,项目中需要链表中的一部分功能,尝试写了一些。

提炼后的需求

有若干字符串,逐一存在链表中,然后在最后统一输出。

  • 每次追加都在链表的最后。
  • 阉割了的链表,没有删除、查询等功能。

上代码

代码语言:javascript
复制
	
#include	<stdio.h>
#include	<string.h>
#include	<stdlib.h>
#include	<memory.h>
#include	<malloc.h>


typedef struct node {
	char data[1024];
	struct node * next;
} Node;

Node* InitList(char[]) ;
void printNode(Node *);
void AddNode(Node *, char* );

int main( void )
{
	int i =99;
	Node * pHead;
	pHead = InitList("1000001\n");

	char temp[512];
	sprintf(temp,"0111111%dA",i);
	AddNode(pHead,temp);
	AddNode(pHead,"111111\n");
	AddNode(pHead,"2222211222\n");
	AddNode(pHead,"3333333\n");
	AddNode(pHead,"4444444444\n");

	printNode(pHead);

	return 0;
	}


Node* InitList(char trailData[]) {
	Node * head = (Node * )malloc(sizeof(Node));
	memset(head->data,0x00,sizeof(head->data));
	strcpy(head->data,trailData);
	head->next = NULL;
	return head;
}


void printNode(Node *head){
    Node *p;
	if(head->data){
	   printf("%s\n",head->data);
	}

	p = head->next;
	while(p != NULL){
	    printf("%s\n",p->data);
	        p = p->next;
	}
	return;
}

void AddNode(Node *head, char trailData[]) {
	Node *currentNode, *newNode, *next;
	currentNode = head;
	next = head->next;

	while (next != NULL) {
		currentNode = next;
		next = next->next;
	}
	
	newNode = (Node * )malloc(sizeof(Node));
	memset(newNode , 0x00,sizeof(newNode));
	strcpy(newNode->data,trailData);

	currentNode->next = newNode;
	return;
}

编译

代码语言:javascript
复制
gcc -Wall test.c -o test

运行

代码语言:javascript
复制
run ./test

结果如下

image.png
image.png

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 提炼后的需求
  • 上代码
  • 编译
  • 运行
  • 结果如下
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档