// 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删除指针,渐渐有些不同的理解。