#ifndef _NODE_H_
#define _NODE_H_
typedef struct _node{
int data;
struct _node *next; //next是一个Node型的指针。
}Node;
void add(Node**, int);
void show(Node*);
void find(Node*, int);
void deleteNode(Node**, int);
void destroyList(Node*);
#endif
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
</pre><pre code_snippet_id="463884" snippet_file_name="blog_20140904_1_885337" name="code" class="cpp">#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
using namespace std;
//typedef struct node_{
// int data;
// struct node_ *next;
//}Node;
int main(int argc, char** argv) {
int num;
Node* head = NULL; //head 是一个Node型的指针, 起初指向NULL.
//作用类似于链表的初始化;
do{
scanf("%d", &num);
if(num != -1)
{
add(&head, num);//只有传入head的指针,才能对head进行修改。
//head本身就是指针了,所以我们传入一个指针的指针;
}
}while (num != -1);
show (head);
cout << "Please input the data you want to find: " << endl;
int number;
cin >> number;
find (head, number);
cout << "Please input the data you want to delete: " << endl;
int number1;
cin >> number1;
deleteNode(&head, number1);
show(head);
destroyList(head);
cout << "after the free of the whole list, the list now is: "
show(head);
return 0;
}
void add(Node** pHead, int num)//pHead是head的指针。传入head, 此时*pHead就是head;
{
/***********************新创建一个Node*************************/
Node* p = (Node*)malloc(sizeof(Node));//p是一个Node指针,
//p指向一片新开辟的空间,该空间是Node大小.
p->data = num;
p->next = NULL;//因为是最新开辟的一个Node,所以将该Node放到链表的末尾。
/*********************找到最后的那个Node***************************/
Node* last = *pHead;//从链表头开始遍历;
if (last != NULL)//如果head不是NULL,说明链表非空的。那么就从头找到链表的尾巴。
{
while(last->next)
{
last = last->next;
}
/****************把新建立的Node链接到链表的尾巴上*********************/
last->next = p; //next也是一个Node型的指针。
}
/****************如果链表还是空的***********************/
else {
*pHead = p;
}
}
void show(Node* head)
{
cout <<"the linked list is: "<<endl;
for(Node *p = head; p; p = p->next)
cout << p->data << " ";
cout << endl;
}
void find(Node *head, int number)
{
int flag = 0;
for (Node *p = head; p; p = p->next)
{
if (p->data == number)
{
flag = 1;
cout << "we've found the number "<< number << endl;
}
}
if (flag == 0)
cout << " we cannot find the number " << number << endl;
}
void deleteNode(Node** pHead, int number)
//我们有对head进行修改,需要传入head的指针
{
int flag = 0;
Node* previous;
Node* p;
for (previous = NULL, p = *pHead; p; previous = p, p = p->next)
{
if (p->data == number)
{
flag = 1;
if (previous)//如果previous指针非空的话
previous->next = p->next;
else
*pHead = p->next;
free(p);
cout << "Deletion is successful" << endl;
break;
}
}
if (flag == 0)
cout << "We can't find the number you want to delete." << endl;
}
void destroyList(Node *head)
{
Node *p, *q;
for (p = head; p; p = q)
{
q = p->next;
free(p);
}
}