创建链表,增删节点
Posted MaNqo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建链表,增删节点相关的知识,希望对你有一定的参考价值。
最近在焦头烂额地复习C语言,个人觉得以下这个案例对链表的学习有很大的用处
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; //单链表的数据域 //struct student data//改有data的
struct Node *next; //单链表的指针域
};
struct Node* createList(){ //创建链表
struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));
headNode->data = 1;
headNode->next = NULL;
return headNode;
}
struct Node* createNode(int data){ //创建结点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void printList(struct Node*headNode){ //打印链表
struct Node* pMove = headNode -> next;
while(pMove){
printf("%d", pMove->data);
pMove = pMove->next;
}
printf("\\n");
}
//插入结点,参数:插入那个链表,插入结点的数据时多少
void insertNodeByHead(struct Node* headNode, int data){
//创建插入的结点
struct Node* newNode = createNode(data);
newNode->next = headNode->next;
headNode-> next = newNode;
}
//指定位置删除
void deleteNodeByAppoin(struct Node* headNode,int posData){
struct Node* posNode = headNode -> next;
struct Node* posNodeFront = headNode;
if(posNode == NULL){
printf("无法删除链表");
}else{
while(posNode -> data != posData){
posNodeFront = posNode;
posNode = posNodeFront->next;
if(posNode == NULL){
printf("没有找到相关信息,无法删除\\n");
return;
}
}
posNodeFront -> next = posNode -> next;
free(posNode);
}
}
int main(){
struct Node* list = createList();
insertNodeByHead(list,1);
insertNodeByHead(list,2);
insertNodeByHead(list,3);
printList(list);
deleteNodeByAppoin(list,2);
printList(list);
system("pause");
// struct Node Node1 = {1, NULL};
// struct Node Node2 = {2, NULL};
// struct Node Node3 = {1, NULL};
// Node1.next = &Node2;
// Node2.next = &Node3;
return 0;
}
以上是关于创建链表,增删节点的主要内容,如果未能解决你的问题,请参考以下文章