记录知识点,用于复试准备中C程序的链表基础操作
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct LinkNode
{
int val;
LinkNode *next;
};
LinkNode* nodeInitial(LinkNode *head)
{
head -> next = NULL;
head -> val = -1;// 带头结点
cout << "初始化完成" << endl;
return head;
}
//尾插法
LinkNode* nodeInsert(LinkNode *head, int x)
{
printf("开始插入数据:%d\n",x);
LinkNode *ans = head;
LinkNode *cur = (LinkNode*) malloc(sizeof(LinkNode));//定义节点类型时一定要为其开辟空间
cur->val = x;
cur->next = NULL;
while(ans->next){
ans = ans->next;
}
ans->next = cur;
return head;
}
//在具体某个位置插入数据
LinkNode* nodeInsertPos(LinkNode *head, int x, int pos)
{
printf("要插入的位置是:%d\n",pos);
LinkNode* cur = head, *pre;
LinkNode *t = (LinkNode*) malloc(sizeof(LinkNode));
t->val = x; // 要插入的节点数据
while(cur && pos--){
pre = cur;
cur = cur->next;
}
if(!cur && !pos){ //插入到链表的最后位置
pre->next = t;
t->next = NULL;
return head;
}
if(!cur && pos){ //若直到链表尾部,pos还没减到0,则说明要插入的位置pos大于链表的长度
printf("输入的位置不合法,请重新输入!\n");
return head;
}
//将节点插入到pos位置
pre->next = t;
t->next = cur;
return head;
}
LinkNode* nodeDelete(LinkNode *head, int pos)
{
LinkNode *cur = head, *pre;//将要删除节点记为cur, 将要删除的前一个节点记为pre
while(cur && pos--){
pre = cur;
cur = cur->next;
}
if(!cur){ //遍历完链表仍未找到要删除的节点位置
printf("输入的下标有误!\n");
return head;
}
pre->next = cur->next;
free(cur);
return head;
}
void nodePrint(LinkNode *head)
{
cout << "打印单链表中的数据:" << endl; //这里cout和printf混着用了,可以自行将其改成printf,或增加cout的头文件
while(head->next){
printf("%d====", head->next->val);
head = head->next;
}
cout << endl;
}
int main()
{
//测试
LinkNode *head = (LinkNode*) malloc(sizeof(LinkNode));
head = nodeInitial(head);
nodePrint(head);
head = nodeInsert(head, 1);
head = nodeInsert(head, 2);
head = nodeInsert(head, 3);
nodePrint(head);
head = nodeInsertPos(head, 5, 4);
nodePrint(head);
head = nodeDelete(head, 2);
nodePrint(head);
}