You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int data;
struct ListNode *next;
} ListNode;
//typedef ListNode *LinkList;
//LinkList head;
//ListNode *p;
ListNode *initLink() {
ListNode *p = NULL;//创建头指针
ListNode *temp = (ListNode *) malloc(sizeof(ListNode));//创建首元节点
//首元节点先初始化
temp->data = 1;
temp->next = NULL;
p = temp;//头指针指向首元节点
//从第二个节点开始创建
for (int i = 2; i < 5; i++) {
//创建一个新节点并初始化
ListNode *a = (ListNode *) malloc(sizeof(ListNode));
a->data = i;
a->next = NULL;
//将temp节点与新建立的a节点建立逻辑关系
temp->next = a;
//指针temp每次都指向新链表的最后一个节点其实就是 a节点这里写temp=a也对
temp = temp->next;
}
//返回建立的节点,只返回头指针 p即可通过头指针即可找到整个链表
return p;
}
void display(ListNode *p) {
ListNode *temp = p;//将temp指针重新指向头结点
//只要temp指针指向的结点的next不是Null就执行输出语句。
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
ListNode *init() {
ListNode *p = NULL;
ListNode *temp = (ListNode *) malloc(sizeof(ListNode));
temp->data = 0;
temp->next = NULL;
p = temp;
for (int i = 1; i <= 5; i++) {
ListNode *a = (ListNode *) malloc(sizeof(ListNode));
a->data = i;
a->next = NULL;
temp->next = a;
temp = a;
}
return p;
}
ListNode *createList() {
//头插法
ListNode *p = NULL;
for (int i = 1; i <= 5; i++) {
ListNode *a = (ListNode *) malloc(sizeof(ListNode));
a->data = i;
a->next = p;
p = a;
}
return p;
}
ListNode *GetNodei(ListNode *head, int i) {
ListNode *p = head;
int j = 1;
while (p != NULL && j < i) {
p = p->next;
++j;
}
if (j == i) {
p->next = NULL;
return p;
} else {
return NULL;
}
}
ListNode *insertLinkList(ListNode *head, int i, int element) {
ListNode *p = head, *s;
int j = 0;
while (p != NULL && j < i) {
p = p->next;
++j;
}
if (p == NULL) {
printf("error\n");
return NULL;
} else {
s = (ListNode *) malloc(sizeof(ListNode));
s->data = element;
s->next = p->next;
p->next = s;
}
return head;
}