江琛

初学单链表

#include <iostream>
using namespace std;

typedef struct node {
int data;
struct node *next;
} Node;

//创建列表 有点类似于c++构造函数
Node *creatList() {
Node *head = (Node *)malloc(sizeof(Node));//创建头结点
head->next = NULL;//初始化指针域
return head;
}

//创建结点 有点类似于c++构造函数
//便于插入删除数据
Node *creatNode(int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

//遍历打印链表
void printList(Node *list) {
if (list->next == NULL) {//为空千万不能赋值
printf("this is a NULL list");
return;
}
Node *pMove = list->next;
while (pMove) {
printf("%d ", pMove->data);
pMove = pMove->next;
}
printf("\n");
}

//头部插入结点
void insertbyHead(Node *list, int data) {
Node *newNode;//初始化结点
newNode = creatNode(data);//构造结点
newNode-> next = list->next;
list->next = newNode;
}

//尾部插入结点
void insertbyEnd(Node *list, int data) {
if (list->next == NULL) { //如果为空不能赋值,直接插入
list->next = creatNode(data);
return;
}
Node *p = list->next; //代理指针 找到最后一个位置
while (p->next) {
p = p->next;
}
p->next = creatNode(data);

}

//指定位置删除
void deleteNode(Node *list, int pos) {
Node *p = list->next;//头节点开始
Node *pre = list; //p的前一个结点
if (p == NULL) {
printf("this is a NULL list\n");
return;
}
while (p) {//双指针遍历链表
if (p->data == pos) {
pre->next = p->next;
free(p);
printf("delete %d successful\n", pos);
return;
}
pre = p;
p = p->next;
}
printf("there is no data:%d\n", pos);
}

int main() {
Node *list = creatList();
insertbyHead(list, 1);
insertbyHead(list, 2);
insertbyHead(list, 3);
deleteNode(list, 5);
printList(list);
return 0;
}

posted on 2022-04-30 11:08  江琛  阅读(29)  评论(0编辑  收藏  举报

导航