C语言实现链表,在数据结构课程中是必须要熟练掌握的。可惜久疏拳法,几乎忘得一干二净,项目中需要链表中的一部分功能,尝试写了一些。
有若干字符串,逐一存在链表中,然后在最后统一输出。
#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;
}
gcc -Wall test.c -o test
run ./test
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。