c++单链表基本操作

下午没事,看数据结构。想到自毕业以后,都没有写过这些东西了。写个链表基本操作,还没完全测试。
#include<iostream>
using namespace std;

/*Node 节点*/
struct Node
{
public:
	Node(int d) { data = d; p = NULL; }
	int data;
	Node *p;
}; 

/*单链表*/
class Link {
private:
	int length;
	Node* head;
	Node* tail;

public:
	Link() { length = 0; head = NULL; tail = NULL; }
	/*通过数组够造*/
	Link(int *arr, int len) {
		length = len;
		Node * tmp = head;
		for (int i = 0; i < len; i++){
			Node* node = new Node(arr[i]);
			if (i == 0){
				head = node;
				tmp = head;
				continue;
			}
			tmp->p = node;
			tmp = node;
		}
		tail = tmp;
	}

	/*打印链表*/
	void printLink() {
		Node * cur = head;
		while (cur!=NULL){
			cout << cur->data << " ";
			cur = cur->p;
		}
		cout << endl;
	}

	/*链表逆序*/
	void reverse() {
		Node* c1, *c2, *c3;
		c1 = head;
		tail = head;
		c2 = head->p;
		while (c2 != NULL) {	//c2 == NULL,说明单节点,无需逆序
			if (c1 == head) 
				c1->p = NULL;
			c3 = c2->p;
			c2->p = c1;
			if (c3->p == NULL) {
				c3->p = c2; 
				head = c3;
				break;
			}
			c1 = c2;
			c2 = c3;
			c3 = c3->p;
		}
	}

	/*获得链表长度*/
	int size() {
		return length;
	}

	/*指定位置插入*/
	void insert(int pos,int data) {
		if (pos > length) {
			tail->p = new Node(data);
		}
		else if (pos<=0){
			Node* t = new Node(data);
			t->p = head;
			head = t;
		}
		else {
			Node* new_node = new Node(data);
			Node* cur = getNode(pos-1);
			new_node->p = cur->p;
			cur->p = new_node;
		}
		length++;
	}

	/*根据位置得到节点指针*/
	Node* getNode(int pos) {
		if (pos<0 || pos>length-1) return NULL;
		int i = 0;
		Node *cur = head;
		while (i<pos){
			i++;
			cur = cur->p;
		}
		return cur;
	}

	/*删除指定位置*/
	void del(int pos) {
		Node* cur = getNode(pos);
		Node* pre = getNode(pos - 1);
		pre->p = cur->p;
		delete cur;
	}

	/*清空链表*/
	void clear() {
		Node *tmp = head;
		while (head != tail){
			tmp = head;
			head = head->p;
			delete tmp;
		}
		delete head;
		head = NULL;
		length = 0;
	}

	/*更改指定位置的节点的值*/
	void update(int pos, int new_date) {
		Node* cur = getNode(pos);
		cur->data = new_date;
	}

	/*查找指定位置的节点的值*/
	void get(int pos) {
		return getNode(pos)->data;
	}

};

int main() {
	int arr[] = { 5,7,9,4,0,1,8,3 };
	Link link(arr, 8);
	link.reverse();
	link.insert(1, 2);
	link.del(2);
	link.update(7, 11);
	link.printLink();
	//link.clear();
	//link.printLink();
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值