c++链表自学笔记

  学习C语言即必须学链表,不过大一上都在弄算法,到期末都没有看链表。
  现在到c++面向对象,发现不行了。只好回头重来,发现还行。


度娘上找的图片,虽然表达不好,但足够了(别太贪心)
c++链表自学笔记

#include
using namespace std;

struct student
{
int num;
char name[20];
struct student *next;//用来连接每个结构体
};

struct student* creat()
{
student *head = NULL, *p1, *p2;
p1 = p2 = (student*)new student;
cout << "enter the num&name:";
cin >> p1->num >> p1->name;

//循环改变p1,p2的指向,p2紧接在p1后面,指向p1
while (p1->num != 0)
{
if (head == NULL)//注意第一个位置是没有其他指针指向它的
{
head = p1;
}
else//不是第一个位置
{
p2->next = p1;
}
p2 = p1;//在p1指向新开的空间之前,p1,p2都是指向同一个区域的
p1 = (student*)new student;//新开辟一块空间,并把p1指向新开的空间
cout << "enter the num&name:";
cin >> p1->num >> p1->name;
}
p2->next = NULL;
return head;//返回首地址
}

void print(student *head)
{
student  *p;
p = head;
cout << endl;
while (p != NULL)//打印当前指向的数据,并把指针指向下一个位置
{
cout << "num:" << p->num << ' ' << "name:" << p->name << endl;
p = p->next;
}
}


struct student* delet(student *head, int num)
{
student *p1, *p2;
p2 = p1 = head;
while (p1->num != num&&p1->next != NULL)//也是循环使用p1,p2
{
p2 = p1;
p1 = p1->next;
}
if (p1 == head)//删除第一个数的话,head就该变成第二个数了
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
return head;
}

struct student* add(student *head, student *newstu)
{
student *p0, *p1, *p2;
p2 = p1 = head;
p0 = newstu;
while (p1->num < p0->num&&p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (p1->num>p0->num)
{
if (p1 == head)
{
head = p0;
}
else
{
p2->next = p0;
}
p0->next = p1;
}
return head;
}

void main()
{
int temp;
student *head;
head = creat();
print(head);
cout << "if you want to delet something?1(yes),2(no)";
cin >> temp;
if (temp == 1)
{
cout << "delet number:";
cin >> temp;
delet(head,temp);
}
print(head);
system("PAUSE");
}

到头来还是要自己仔细看懂,光是想想是没有用的,只要看懂一个代码,然后自己编写一下,就马上会了。。。。。。。
干巴爹

你可能感兴趣的:(c)