这个是引用方式,链表分带头结点与不带头结点,但是都可以用
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//带头结点
LNode* create(int Array[]){
LNode *p, *pre, *head;
head = new LNode;
head->data = NULL;
pre = head;
for (int i = 0; i < 8; i++){
p = new LNode;
p->data = Array[i];
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
//不带头结点
LNode* noheadcreate(int Array[]){
LNode *p, *pre, *head = NULL;
/*node *head = NULL;*/
pre = head;
for (int i = 0; i < 8; i++){
//此处对头结点进行单独处理,不存在pre->next;
if (head == pre){
p = new LNode;
p->next = NULL;
p->data = Array[i];
pre = p;
head = p;
}
p = new LNode;
p->data = Array[i];
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
///递归删除不带头结点的单链表中值为x的结点(带不带头结点都一样)
//经过测试,带不带头结点都是可以实现效果,
//有点晕,这是因为引用吗?不带头结点的时候竟然没有问题
void Del_x_1(LinkList &L, int x){//引用方式不会断链
LNode *p;
if (L == NULL) return;
if (L->data == x){
p = L;
L = L->next;
free(p);
Del_x_1(L, x);
}
else
{
Del_x_1(L->next, x);
}
}
int main(){
//用不带头结点的方式创建单链表L01
int Array01[8] = { 1, 3, 6, 6, 9,5,4,3 };
LNode* L01 = noheadcreate(Array01);
Del_x_1(L01,6);
//用带头结点的方式创建单链表L02
int Array02[8] = { 1, 3, 6, 6, 9, 5, 4, 3 };
LNode* L02 = create(Array02);
Del_x_1(L02, 3);
//不用打印函数了,直接写吧,正好看看带不带头结点的打印方式不同之处
cout << "递归删除不带头结点的单链表中值为6的结点:";
while (L01->next != NULL){
cout << L01->next->data;
L01 = L01->next;
};
cout << endl;
cout << "递归删除带头结点的单链表中值为3的结点:";
while (L02->next != NULL){
cout << L02->next->data;
L02 = L02->next;
};
cout << endl;
return 0;
}
在介绍一个普通的方法,使用指针写
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *Linklist;
//带头结点单链表的创建
LNode* create(int Array[]){
LNode *p, *pre, *head;
head = new LNode;
head->data = NULL;
pre = head;
for (int i = 0; i < 5; i++){
p = new LNode;
p->data = Array[i];//链表的data域直接用数组的值传, 不直接输入了
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
void delete_x_1(LNode *head, int x){//head为单链表头结点,删除结点的值为x
LNode *l = head;
LNode *p = head->next;
while (p != NULL){
if (p->data == x){
l->next = p->next;
free(p);
p = l->next; //要加上这句啊,因为直接销毁p后面又将p的地址给l,因为已经销毁了直接就为空了
} //在网上看了别人的代码是没有这句了,运行时出问题的
l = p;
p = p->next;
}
}
int main(){
int Array01[5] = { 1, 3, 5, 7, 9 };
LNode* L01 = create(Array01);
delete_x_1(L01, 5);
while (L01->next != NULL){
cout << L01->next->data;
L01 = L01->next;
}
return 0;
}