链表增删改查

#include <iostream>
using namespace std;
typedef int T;
class List{
	struct Node{
		T data;
		Node *next;
		Node(const T &d=T()):data(d),next(NULL){};//node构造函数,T()零初始化
	};
	Node *head;
	int len;
public:
	List():head(NULL),len(0){};
	void push_front(const T&d){//前插
//		Node *p=new Node(d);
//		p->next=head;
//		head=p;
		insert(d,0);
	}
	List& push_back(const T&d){//尾插
		insert(d,size());
		return (*this);
	}
	int size()const{//遍历
		return len;
	}
	Node *&getptr(int pos)//找到指定位置的指针
	{
		if(pos<0||pos>size()) pos=0;
		if(pos==0) return head;
		Node *p=head;
		for(int i=1;i<pos;i++){
			p=p->next;
		}
		return (*p).next;
	}

	void insert(const T&d,int pos){//插入任意位置
		Node *&p=getptr(pos);
		Node *n=new Node(d);
		n->next=p;
		p=n;
	}

	void travel()const{//遍历
		Node *p=head;
		while(p!=NULL){
			cout<<p->data<<' ';
			p=p->next;
		}
		cout<<endl;
	}

	void clear(){//释放
		while(head!=NULL){
			Node *p=head->next;
			delete head;
			head=p;
		}
	}
	void erase(int pos){
		if(pos<0||pos>=size()) return;
		Node *pn=getptr(pos);
		Node *p=pn;
		pn=pn->next;
		delete p;
		--len;
	}

	int find(const T& d)const
	{
		int pos=0;
		Node *p=head;
		while(p!=NULL){
			if(p->data==d) return pos;
			p=p->next;
			pos++;
		}
		return -1;
	}
	void remove(const T&d){//删除
		int pos;
		while((pos=find(d))!=-1)
			erase(pos);
	}
	void set(int pos,const T&d){//修改
		if(pos<0||pos>=size())return ;
		getptr(pos)->data=d;
	}
	~List(){clear();};
};

int main(void)
{
	List l;
	l.push_front(10);
	l.push_front(20);
	l.push_front(30);
	l.push_back(50);
	l.insert(40,2);
	l.travel();
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍一下 C 语言中动态链表增删改查操作。 首先,我们需要定义一个链表结构体: ```c typedef struct Node { int data; struct Node *next; } Node, *LinkedList; ``` 其中,`data` 表示链表节点中存储的数据,`next` 表示指向下一个节点的指针。 接下来,我们可以实现链表的创建操作: ```c LinkedList createList() { LinkedList head = (LinkedList)malloc(sizeof(Node)); head->next = NULL; return head; } ``` 这个函数会返回一个链表头节点的指针,也就是一个空链表。 接下来,我们可以实现链表节点的插入操作: ```c void insertNode(LinkedList L, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = L->next; L->next = newNode; } ``` 这个函数会在链表头节点后插入一个新的节点。 接下来,我们可以实现链表节点的删除操作: ```c void deleteNode(LinkedList L, int data) { Node *p = L; while (p->next != NULL && p->next->data != data) { p = p->next; } if (p->next == NULL) { printf("Not found!\n"); return; } Node *tmp = p->next; p->next = tmp->next; free(tmp); } ``` 这个函数会在链表中查找指定数据的节点,并删除它。 最后,我们可以实现链表节点的查找操作: ```c Node *findNode(LinkedList L, int data) { Node *p = L->next; while (p != NULL && p->data != data) { p = p->next; } return p; } ``` 这个函数会在链表中查找指定数据的节点,并返回它的指针。 以上就是 C 语言中动态链表增删改查操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值