单链表的基本操作
包括:初始化,插入,删除,逆置,求表长
- 定义链表的数据结构
struct node {
int data;
node *next;
};
- 初始化链表
node* create(node* head) {
head = new node;
head->next = NULL;
return head;
}
- 链表的插入(头插法)
node* insert(node *head, int value) {
//new node
node *new_node = new node;
new_node->data = value;
//record head->next
node *temp;
temp->next = head->next;
head->next = new_node;
new_node->next = temp->next;
return head;
}
- 链表的删除,删除第i个节点,(有一个空的头结点作为第0个)
//测试集,空指针,空链表,删除的位置是负数,删除的位置在链表中,删除的位置超过链表的长度
node* delete_by_position(node *head, int n) {
//空指针
if(!head) {
cout<<"NULL point!"<<endl;
return head;
}
//指针应该定位到第n-1个元素
node *p = head;
//已经数了多少个了,因为要删除第n个元素 ,所以应该数了n-1次,然后p指针指向第n-1个元素
int count = 0;
//move to position of n-1
while(p->next && n-1>count) {
p = p->next;
count++;
}
if(n-1 != count || !p->next) {
cout<<"node not found!"<<endl;
return head;
}
//if found, delete that node
node* temp = p->next;
p->next = temp->next;
delete temp;
return head;
}
- 链表的删除,删除节点值为value的第一个元素
//测试集,空指针,空链表,删除的元素在链表中,删除的元素不在链表中
node* delete_by_value(node* head, int value) {
if (!head) {
cout<<"node not found!"<<endl;
return head;
}
bool flag =false;
node *p = head;
while (p->next) {
if (p->next->data == value) {
flag = true;
break;
}
p = p->next;
}
if(flag) {
node* temp = p->next;
p->next = temp->next;
free temp;
} else {
cout<<"node not found!"<<endl;
}
return head;
}
- 遍历链表
void display (node *head) {
if(!head) {
return ;
}
node* p = head;
while(p->next) {
cout<<p->next->data<<endl;
p = p->next;
}
}
- 求链表的长度
int getLength(node *head) {
if (!head) {
return -1;
}
int count = 0;
node *p = head;
while(p->next) {
count++;
p = p->next;
}
return count;
}
- 链表逆置 这里采用原地逆置,通过头指针和额外定义的两个指针不断移动更改链接来实现逆置
node* reverse(node *head) {
//NULL point
if(!head) {
cout<<"it is NULL point!"<<endl;
return head;
}
node *a,*p;
//initialize
a = head->next;
while(a->next) {
p = a->next;
a->next = p->next;
p->next = head->next;
head->next = p;
}
return head;
}
主函数
int main () {
//new head
node* head;
//创建头结点
head = create(head);
//输入n个元素,并以头插的形式插入到链表
int n;
cin>>n;
while(n-->0) {
int value;
cin>>value;
head = insert(head,value);
}
//遍历
display(head);
//删除第n个元素 注意n取值
cin>>n;
head = delete_by_position(head,n);
//删除元素值为value的第一个节点
int value;
cin>>value;
head = delete_by_value(head,value);
//链表逆置
head = reverse(head);
display(head);
//求表长
cout<<getLength(head)<<endl;
display(head);
return 0;
}