当前位置:首页 > 编程相关 > 正文内容

c实现单链表

Nietzsche2021-01-29 20:05:23编程相关42

#include <stdio.h>

typedef struct Node

{

int data;

struct Node* next;

}NODE,*LPNODE;

LPNODE createHead()

{

LPNODE headNode = (LPNODE)malloc(sizeof(NODE));

headNode->next = NULL;

return headNode;

}


LPNODE createNode(int data)

{

LPNODE newNode = (LPNODE)malloc(sizeof(NODE));

newNode->data = data;

newNode->next = NULL;

return newNode;

}

void insertNodeByHead(LPNODE headNode, int data)

{

LPNODE newNode = createNode(data);

newNode->next = headNode->next;

headNode->next = newNode;

}

void insertNodeByTail(LPNODE headNode, int data)

{

LPNODE pMove = headNode->next; 

while (pMove!=NULL&&pMove->next != NULL)

{

pMove = pMove->next;

}

LPNODE newNode = createNode(data);

if (pMove != NULL)

pMove->next = newNode;

else

headNode->next = newNode;

}


void printList(LPNODE headNode)

{

LPNODE pMove = headNode->next;

while (pMove)

{

printf("%d\t", pMove->data);

pMove = pMove->next;

}

printf("\n");

}

int main()

{

LPNODE list = createHead();

for (int i = 0; i < 4; i++)

{

insertNodeByHead(list, i);

}

printList(list);

return 0;

}


版权声明:作为笔记收集,仅供学习使用.

分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。