链表头部插入和尾部插入

链表头部插入和尾部插入

头部插入

void NodeList::addToHead()
{
	for (int i = 0; i < arrrlens; i++)
	{
		int node = arr_1[i];
		Node* p = new Node(node, NULL);
		if (i == 0) {
			head = p;
		}
		else {
			p->next = head;
			head = p;
		}
	}
}

尾部插入

void NodeList::addToTail()
{ 
	Node *fp = head;
	for (int i = 0; i < arrrlens; i++)
	{
		int node = arr_2[i];
		Node* p = new Node(node, NULL);
		fp->next = p;
		fp = p;
	}
	//删除头部为空节点
	Node* newHead = head->next;
	delete head;
	head = newHead;
}

源码

#include<stdio.h>
#include<iostream>
using namespace std;
//测试数据
const int arrrlens = 5;
int arr_1[arrrlens] = { 9, 7, 5, 3, 1 };
int arr_2[arrrlens] = { 0, 2, 4, 6, 8 };
class Node {
public:
	//构造函数,创建一个节点
	Node(int el = NULL, Node* ptr = NULL) {
		infor = el;
		next = ptr;
	}
	int infor;
	Node* next;
};
class NodeList {
public:
	NodeList() {
		head = new Node();
	}
	~NodeList() {
		delete head;
	}
	//节点插入头部
	void printList();
	void addToHead();
	void addToTail();
	Node* getHead();
	//Node* mergeTwoOrderLists(NodeList*, NodeList*);
	
private:
	Node* head;
};
//头部插入法链表顺序与输入数据顺序相反
Node* NodeList::getHead()
{
	return head;
}
void NodeList::addToHead()
{
	for (int i = 0; i < arrrlens; i++)
	{
		int node = arr_1[i];
		Node* p = new Node(node, NULL);
		if (i == 0) {
			head = p;
		}
		else {
			p->next = head;
			head = p;
		}
	}
}
void NodeList::addToTail()
{ 
	Node *fp = head;
	for (int i = 0; i < arrrlens; i++)
	{
		int node = arr_2[i];
		Node* p = new Node(node, NULL);
		fp->next = p;
		fp = p;
	}
	//删除头部为空节点
	Node* newHead = head->next;
	delete head;
	head = newHead;
}

void NodeList::printList()
{
	Node* p = head;
	while (p != NULL)
	{
		printf("%d ", p->infor);
		p = p->next;
	}
	printf("\n");
}
int main()
{
	NodeList nlist_1, nlist_2;
	nlist_1.addToHead();
	nlist_2.addToTail();
	nlist_1.printList();
	nlist_2.printList();
}
点赞