C++实现
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
int n = 0; //节点个数
//单链表的创建,尾插法
struct node *create(struct node *head)
{
//p为待插入的节点,q始终指向链表的最后一个节点
struct node *p, *q;
p = q = new node;
cin>>p->data;
p->next = NULL;
//当输入值<=0时结束输入
while(p->data > 0)
{
if(head == NULL)
head = p;
else
q->next = p;
q = p;
n++;
p = new node;
cout<<"输入大于0的值,小于等于0则结束,值的存放地址为:p_addr = "<<p<<endl;
cin>>p->data;
p->next = NULL;
}
delete(p);
p = NULL;
q->next = NULL;
cout<<"输入结束"<<endl;
return head;
}
//单链表打印
void print(struct node *head)
{
struct node *p;
p = head;
cout<<"链表打印开始!"<<endl;
cout<<"节点个数为: "<<n<<endl;
while(p != NULL)
{
cout<<"data = "<<p->data<<";地址为:"<<p<<endl;
p = p->next;
}
cout<<"链表打印结束!"<<endl;
}
//单链表删除指定值节点
struct node *del(struct node *head, int num)
{
struct node *p;
p = head; //p,q指针指向头节点
cout<<"链表删除开始!"<<endl;
if(head != NULL) //链表不为空
{
if(p->data == num) //若头节点为目标节点
{
delete(p);
head = head->next;
n--;
}
else
{
//p->next为目标节点
while(p->next!=NULL && p->next->data != num)
p = p->next;
if(p->next != NULL)
{
p->next = p->next->next;
n--;
}
else
cout<<"没有找到目标节点!"<<endl;
}
}
else
cout<<"链表为空!"<<endl;
cout<<"链表删除结束!"<<endl;
return head;
}
//单链表在指定位置插入(从0开始)
struct node *ins(struct node *head)
{
int index, num; //待插入节点数据及位置
int temp = 0;
struct node *p, *q; //p节点为待插入节点
cout<<"输入待插入节点数据及位置:"<<endl;
cin>>num>>index;
p = new node;
p->data = num;
p->next = NULL;
q = head;
if(index == 0) //插入位置为头部
{
p->next = head;
head = p;
}
else
{
//q节点的下一个节点为待插入的目标位置
while(q->next!=NULL && temp+1 != index)
{
q = q->next;
temp++;
}
//插入位置在链表中间或尾部
if(q->next != NULL || temp+1==index)
{
p->next = q->next;
q->next = p;
n++;
}
else
cout<<"指定位置不合法!"<<endl;
}
return head;
}
int main()
{
struct node *head;
head = NULL;
/***********创建****************/
head = create(head);
/***********打印****************/
print(head);
/***********删除****************/
head = del(head, 1);
print(head);
/***********插入****************/
head = ins(head);
print(head);
return 0;
}