C++链表练习

线性表是最简单的数据组织形式,通过单向链表我们可以建立小表单存储一些简单的数据。
下面就来做一个仓储管理的练习:
在这里插入图片描述在这里插入图片描述
Main函数已经给出:
在这里插入图片描述
那我们先定义好链表Goods类:

class Goods {
public:
	Goods(int sW) {
		singleWeight = sW;
		totalWeight += singleWeight;//构造函数增上单重量
	}
	~Goods() {
		totalWeight -= singleWeight;//析构函数减去单重量
	}
	int getSW() {
		return singleWeight;
	}
	static int TotalWeight() {
		return totalWeight;
	}	
	Goods * next;
private:
	static int totalWeight;//总重量
	int singleWeight;//单货重量
};

再写买进卖出函数:

//买进
void purchase(Goods *& front, Goods *rear, int w) {
	Goods *p = NULL;
	if (!front) {
		rear = new Goods(w);
		front = rear;
		return;
	}
	for (rear = front; rear; p = rear, rear = rear->next);//迭代至列尾
	rear = new Goods(w);
	p->next = rear;
}
//卖出
void sale(Goods *& front, Goods *rear) {
	if (!front) {
		cout << "库存已空" << endl;
		return;
	}
	rear = front->next;
	delete front;
	front = rear;
}

然后多定义个遍历链表方法:

void showList(Goods * head) {
	while (head) {
		cout << head->getSW() << ends;
		head = head->next;
	}
	cout << endl;
}

结果如下:
在这里插入图片描述
效果实现,目标达成!

以下是一些C++链表练习题及对应代码示例: 1. **反转链表**:将一个单链表反转。 ```cpp /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *cur = head, *pre = nullptr, *next = nullptr; while(cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } }; ``` 此代码通过迭代的方式,依次改变链表节点的指向,实现链表反转 [^1]。 2. **反转链表(另一种实现)**: ```cpp struct ListNode { int val; struct ListNode *next; }; typedef struct ListNode LN; struct ListNode* reverseList(struct ListNode* head) { if (head==NULL) return head; LN *n1, *n2, *n3; n1 = NULL; n2 = head; n3 = head->next; while(n2) { n2->next = n1; n1 = n2; n2 = n3; if(n3) n3 = n3->next; } return n1; } ``` 同样是反转链表的功能,采用不同的变量命名和逻辑流程 [^2]。 3. **查找两个链表的交点**:找出两个单链表相交的起始节点。 ```cpp struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { struct ListNode *cur1 = headA; struct ListNode *cur2 = headB; int countA = 0, countB = 0; while(cur1) { ++countA; cur1 = cur1->next; } while(cur2) { ++countB; cur2 = cur2->next; } //此时的count就记录了两个链表的长度 cur1 = headA; cur2 = headB; int gap = abs(countA - countB); if(countA < countB) //B链更长,应该B先走差距步,让俩个链表起始位置一样 { while(gap--) { cur2 = cur2->next; } } else { while(gap--) { cur1 = cur1->next; } } //走到这两个链表就是一样长 //假设两个链表相交那么走会在末尾之前找到一个节点,两个val一样 while(cur1) { if(cur1 == cur2) { return cur2; } else { cur1 = cur1->next; cur2 = cur2->next; } } return NULL; } ``` 该代码先计算两个链表的长度,然后让长链表的指针先走长度差的步数,最后同时移动两个指针,找到相交节点 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值