只要求写插入和删除代码,熟悉链表的题目
链表的问题主要是出在结尾和头部的添加(这里由于题目说明,头节点是不会插入的),所以只需要考虑
中间插入
尾部插入
头部删除
中间删除
尾部删除(其实尾部和中间是一样的,只不过next指向NULL罢了)
弄清楚各自操作改变哪些量即可
#include<iostream> typedef struct node { int data; //存储数据 struct node* next; //指向下一个节点的指针 } NODE; NODE* insertLinklist(NODE* head, int tar, int val) { if(head == NULL) { NODE* temp = new NODE; temp->next = NULL; temp->data = val; return temp; }//空则返回temp指针 NODE* temp = head; while(temp->data != tar) { //题目设定肯定找得到tar temp = temp->next; } NODE* insert = new NODE; insert->data = val; if(temp->next == NULL) { insert->next = NULL; temp->next = insert; } else { insert->next = temp->next; temp->next = insert; } return head; } NODE* deleteLinklist(NODE* head, int tar) { if(head == NULL) return NULL; if(head->data == tar) { NODE* temp = head->next; delete head; return temp; } NODE* temp = head; while(temp->next != NULL && temp->next->data != tar ) temp = temp->next; if(temp->next->data == tar) { NODE* del = temp->next; temp->next = del->next; delete del; } else if(temp->next == NULL) {} return head; }