C语言单向链表插入和查找

创建实头结点链表

#include <stdio.h>

typedef struct Node {

int val;

struct Node* next;

}Node, * PNode;

PNode NodeAppend(PNode head, int data) {

PNode p = (PNode)malloc(sizeof(Node));

p->next = NULL;

PNode pr = head;

if (head == NULL) {

head = p;

p->val = data;

}

else {

while (pr->next != NULL) {

pr = pr->next;

}

pr->next = p;

p->val = data;

}

return head;

}

int main() {

PNode head = NULL;

int arr[] = { 1,2,3,4,5,6 };

int size = sizeof(arr) / sizeof(int);

for (int i = 0; i < size; i++) {

head = NodeAppend(head, arr[i]);

}

return 0;

}

头插

#include<stdio.h>

typedef struct node {

int val;

struct node* next;

}node;

void creatnode(node* head, int n) {

node* p;

head->next = NULL;

for (int i = 1; i <= n; i++) {

p = (node*)malloc(sizeof(node));

scanf("%d",&p->val);

p->next = head->next;

head->next = p;

}

}

int main() {

node* head = (node*)malloc(sizeof(node));

int n;

scanf("%d",&n);

creatnode(head,n);

return 0;

}

尾插

#include<stdio.h>

typedef struct node {

int val;

struct node* next;

}node;

void creatnode(node* head, int n) {

node* p;

head->next = NULL;

           node* s = head;

for (int i = 1; i <= n; i++) {

p = (node*)malloc(sizeof(node));

scanf("%d",&p->val);

p->next = NULL;

   s->next = p;

s = p;

}

}

int main() {

node* head = (node*)malloc(sizeof(node));

int n;

scanf("%d",&n);

creatnode(head,n);

return 0;

}

通过序号查找节点

node* getnode(node* head, int n) {

node* p = head->next;

int i = 1;

while (i < n && p != NULL) {

p = p->next;

i++;

}

if (p == NULL) {

printf("妹找着");

return NULL;

}

if (i == n) {

return p;

}

}

通过val值查找结点

node* getnode(node* head, int key) {

node* p = head->next;

while (p != NULL&&p->val!=key) {

p = p->next;

}

if (p == NULL) {

printf("妹找着");

return NULL;

}

if (p->val== key) {

return p;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值