小白也能学会的链表(C语言)
typedef struct link{
int val;
struct link* next;
}Link
struct ListNode* insertNode(
struct ListNode* head, struct ListNode* nodeInsert, int position) {
if (head == NULL) {
return nodeInsert;
}
int size = getLength(head);
if (position > size + 1 || position < 1) {
printf("位置参数越界");
return head;
}
// 插入节点到头部
if (position == 1) {
nodeInsert->next = head;
head = nodeInsert;
return head;
}
struct ListNode* pNode = head;
int count = 1;
while (count < position - 1) {
pNode = pNode->next;
count++;
}
nodeInsert->next = pNode->next;
pNode->next = nodeInsert;
return head;
}
删除与插入的操作大同小异,不再列举
//查找元素
ListNode* findNode(struct ListNode* p,int val){
struct ListNode* temp = p;
while(temp&&temp->val!=val){
temp = temp->next;
}
if(temp && temp->val == val){
return(temp);
}
else{
return null;
}
}
//打印链表
void printList(struct ListNode* p) {
struct ListNode* temp = p;//temp指针用来遍历链表
//只要temp指向结点的next值不是NULL,就执行输出语句。
while (temp) {
// struct ListNode* f = temp;//准备释放链表中的结点
printf("%d ", temp->val);
temp = temp->next;
// free(f);
}
printf("\n");
}
//获取链表的长度
int32_t getLength(struct ListNode* p) {
struct ListNode* temp = p;//temp指针用来遍历链表
int length=0;
//只要temp指向结点的next值不是NULL,就执行输出语句。
while (temp) {
// struct ListNode* f = temp;//准备释放链表中的结点
length++;
temp = temp->next;
// free(f);
}
return length;
}