单项链表的头插入法和尾插入法

//单项链表的头插入法和尾插入法。
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
//头插法
Node* BuildFromHead()
{
Node *head = NULL;
int x;
cin >> x;
while (x != -1)
{
Node* p = new Node;
p->data = x;
p->next = NULL;
if (head == NULL)
{
head = p;
}
else
{
p->next = head;
head = p;
}
cin >> x;
}
return head;
}
//尾插法
Node* BuildFromTail()
{
Node *Head = NULL;
Node*Tail = NULL;
int x;
cin >> x;

while (x != -1)
{
Node*p = new Node;
p->data = x;
p->next = NULL;
if (Head == NULL)
{
Head = Tail = p;
}
else
{
Tail->next = p;
Tail = p;
}
cin >> x;

}
return Head;
}

void display(Node*head)
{
while (head)
{
cout << head->data << endl;
head = head->next;
}
}

void destroy(Node*head)
{
while (head)
{
Node*p = head;
head = head->next;
delete p;
}
}

int main()
{
Node *head = BuildFromHead();
display(head);
destroy(head);
cout << "--------------" << endl;
Node*head1 = BuildFromTail();
display(head1);
destroy(head1);
return 0;
}

打印结果:

猜你喜欢

转载自www.cnblogs.com/c-w-l-110120/p/9652322.html