创建实头结点链表
#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;
}
}