链表的增删改查
链表的创建(两种方法):
头插法:


尾插法:


#include <malloc.h>
#include "stdio.h"
typedef struct LNode{
int data; //数据域
struct LNode *next;//指针域
}ListNode;
//头插法创建链表
ListNode* headInsert(ListNode *&node){ //传递指针地址
ListNode *temp;
int input;
//创建头结点
node = (ListNode*)malloc(sizeof(ListNode));
//初始为空链表
node->next = NULL;
printf("insert num you input, end when input num=-1\n");
while(1){
scanf("%d", &input);
if(input == -1)
break;
// printf("insert num you input, end when input num=-1\n");
temp = (LNode*) malloc(sizeof(LNode));
//替换
temp->data = input;
temp->next = node->next;
//覆盖
node->next = temp;
//输入-1结束循环
}
return node;
}
//尾插法创建链表
ListNode* tailInsert(ListNode *&node){
node = (ListNode*)malloc(sizeof(ListNode));
//创建临时结点
ListNode *temp = NULL, *tempNode = node;
int input;
printf("insert num you input, end when input num=-1\n");
while(1){
scanf("%d", &input);
if(input == -1)
break;
temp = (ListNode*)malloc(sizeof(ListNode));
//新建
temp->data = input;
//连接新结点
tempNode->next = temp;
//更新 tempNode 的位置使其指向最新的位置
tempNode = temp;
}
//没有新结点插入, 则下一个结点为 NULL
tempNode->next = NULL;
return node;
}
//查看链表, 遍历链表
void viewList(ListNode *node){
//略去头结点
ListNode* view = node->next;
while(view != NULL){
printf("%d\n", view->data);
view = view->next;
}
}
int main(){
ListNode *node = NULL;
node = (ListNode*)malloc(sizeof(ListNode));
//头插法创建链表
//viewList(headInsert(node));
//尾插法创建链表
viewList(tailInsert(node));
return 0;
}

浙公网安备 33010602011771号