简单链表的创建,插入和删除
用c++定义链表结点,以及分别用头插法和尾插法创建生成链表,删除链表中指定数值大小的结点等。
struct Node {
int data;
Node *next;
};
Node *Head(Node *head) //头插法创建链表
{
Node *p=nullptr;
int a;
cout << "请输入链表中每一个结点元素的值:以-1结束" << endl;
cin >> a;
while (a != -1)
{
p = new Node;
p->data = a;
if (!head)
{
head = p;
head->next = NULL;
}
else
{
p->next = head;
head = p;
}
}
return head;
}
Node *Tail(Node *tail) //尾插法创建链表
{
Node *head = NULL;
int a;
Node *ptr = 0;
cin >> a;
while (a != -1)
{
ptr = new Node;
ptr->data = a;
if (!head)
{
tail = ptr;
head = tail;
}
else
{
tail->next = ptr;
tail = ptr;
}
}
if (head)
tail->next = NULL;
return tail;
}
Node *Insert(Node *head, Node *p) //有序地插入一个结点
{
Node *p1=head, *p2=p1->next;
if (!head)
{
head = p;
p->next = NULL;
}
else
{
if (head->data == p->data)
{
p->next = head;
head = p;
}
else
{
while (p2->data < p->data&&p2->next != NULL)
{
p1 = p2;
p2 = p2->next;
}
if (p2->data<p->data)
{
p2->next = p;
p->next = NULL;
}
else
{
p->next = p2;
p1->next = p;
}
}
}
}
Node *Sort(Node *head) //有序创建一个链表(升序)
{
Node *p = nullptr;
int opt = 0;
cin >> opt;
while (opt != -1)
{
p = new Node;
p->data = opt;
head = Insert(head, p);
}
}
Node *Delete(Node *head, int num) //删除链表中值为num的结点
{
Node *p1 = 0, *p2 = 0;
Node *q = new Node;
if (!head)
{
cout << "链表为空!\n";
return NULL;
}
if (head->data ==
```cpp
num)
{
q = head;
head = head->next;
delete q;
}
else
{
p1 = head;
p2 = p1->next;
while (p2->data != num && p2->next != NULL)
{
p1 = p2;
p2 = p2->next;
}
if (p2->data== num)
{
p1->next = p2->next;
delete p2;
}
else cout << "链表上没有要删的结点!\n" << endl;
}
return head;
}