c++指针复习

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

class Node
{
public:
	int node;
	Node* next;

	Node(int i) :node(i), next(0){}
};

Node* create(int i, Node* &head)//按引用返回,修改head值
{
	if (head == 0)//no head,just create new head
	{
		head = new Node(i);
	}
	else//if we have head,just put new Node in the last position
	{
		Node* p = head;
		while (p->next != 0)//find the last node in this list
		{
			p = p->next;
		}
		p->next = new Node(i);
		p = 0;
		delete p;
	}
	return head;

}

void print_chain(Node* head)//print chain
{
	while (head != 0)
	{
		cout << head->node << "\t";
		head = head->next;
	}
}

int chain_length(Node * head)
{
	//get the length of chain
	int L = 0;
	Node* p = head;

	while (p != 0)
	{
		L++;
		p = p->next;
	}
	cout << endl;
	cout << "the length of this chain is " << L << endl;
	p = 0;
	delete p;
	return L;
}
Node* remove_node(int n, Node* &head)
{
	//n可以大于链表的最大长度,将其作为循环来处理
	int L = chain_length(head);
	int n_ = n%L;
	Node *p = head;
	if (n_ == 0)
	{
		head = head->next;
		delete p;
	}

	for (int i = 0; i < n_-1; i++)
	{
		p = p->next;
	}
	Node *q = p->next;
	p->next = p->next->next;
	delete q;
	p = 0;
	return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
	Node *head = 0;
	create(1, head);
	create(2, head);
	create(3, head);
	create(4, head);
	print_chain(head);
	chain_length(head);
	remove_node(2,head);
	print_chain(head);

	return 0;
}


过了好久没有复习,完全记不起来,温故而知新,回过头来发现原先不太理解的delete删除指针,渐渐有些不同的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值