删除链表函数:
void delete_node(int index){
if(head==NULL){
return;
}
Node* current_node=head;
int count=0;
if(index==0){
head=head->next;
delete current_node;
return;
}
while(current_node->next!=NULL&&count<index-1){
current_node=current_node->next;
count++;
}
if(count==index-1&¤t_node->next!=NULL){
Node* delete_node=current_node->next;
current_node->next=delete_node->next;
delete delete_node;
}
}
反转链表函数:
void reverse(){
if(head==NULL){
return;
}
Node *next_node,*current_node;
current_node=head->next;
head->next=NULL;
while(current_node!=NULL){
next_node=current_node->next;
current_node->next=head;
head=current_node;
current_node=next_node;
}
}
循环链表:
注意head代表头结点,也代表尾节点
void insert(Node *node, int index) {
if (head == NULL) {
head = node; //当只有一个节点时head的next就是head自己
head->next = head;
return;
}
if (index == 0) {
node->next = head->next; //在head后插入
head->next = node;
return;
}
Node *current_node = head->next;
int count = 0;
while (current_node != head && count < index – 1) {
current_node = current_node->next;
count++;
}
if (count == index – 1) {
node->next = current_node->next;
current_node->next = node;
}
if (node == head->next) {//如果把node插在了head后面则将head设置为node
head = node;
}
}
网友评论