// ListOperate.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "ListData.h"
int _tmain(int argc, _TCHAR* argv[])
{
StudentDataSet StudentSet;
Student* head = StudentSet.CreateNode();
StudentSet.Print(head);
Student* rever = StudentSet.Reverse(head);
StudentSet.Print(rever);
Student* sort = StudentSet.BubbleSort(head);
StudentSet.Print(sort);
return 0;
}
#ifndef LISTDATA_H_
#define LISTDATA_H_
#include
#include
#include
#define LEN sizeof(Student)
struct Student
{
long num;
char name[20];
float score;
Student *next;
};
class StudentDataSet
{
public:
StudentDataSet();
~StudentDataSet();
public:
Student* CreateNode();
Student* Reverse(Student *head);
void Print(Student *head);
Student* BubbleSort(Student *head);
private:
Student stu;
};
#endif
#include "ListData.h"
int n = 0;
StudentDataSet::StudentDataSet()
{
}
StudentDataSet::~StudentDataSet()
{
}
Student* StudentDataSet::CreateNode()
{
Student *head;
Student *p1 ;
Student *p2 ;
p1 =(Student*) malloc(LEN);
p2 = p1;
head = NULL;
printf("Please input %d node -- num,name,score:",n + 1);
scanf("%d,%s,%f",&(p1->num),p1->name,&(p1->score));
while (p1->num!=0)
{
n += 1;
if (n == 1)
{
head = p1;
p2->next = NULL;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (Student *)malloc(LEN);
printf("Please input %d node -- num,name,score:",n + 1);
scanf("%ld,%s,%f",&(p1->num),p1->name,&(p1->score));
}
p2->next = NULL;
free(p1);
p1 = NULL;
return head;
}
Student* StudentDataSet::Reverse( Student *head )
{
Student *p;
Student *p1; /*存储返回结果*/
Student *p2; /*源结果节点一个一个取*/
p1 = NULL; /*开始颠倒时,已颠倒的部分为空*/
p2 = head; /*p2指向链表的头节点*/
while (p2 != NULL)
{
p = p2->next;
p2->next = p1;
p1 = p2;
p2 = p;
}
head = p1;
return head;
}
void StudentDataSet::Print( Student *head )
{
Student *p;
printf("\n Now , These %d records are:\n",n);
p = head;
if(head != NULL) /*只要不是空链表,就输出链表中所有节点*/
{
printf("head is %o\n", head); /*输出头指针指向的地址*/
do
{
printf(" %o %ld %s %f %o\n", p, p->num,p->name, p->score, p->next);
p = p->next;
/*移到下一个节点*/
} while (p != NULL);
}
}
Student* StudentDataSet::BubbleSort( Student *head )
{
Student *endpt; /*控制循环比较*/
Student *p; /*临时指针变量*/
Student *p1;
Student *p2;
p1 = (Student *)malloc(LEN);
p1->next = head; /*注意理解:我们增加一个节点,放在第一个节点的前面,主要是为了便于比较。因为第一个节点没有前驱,我们不能交换地址。*/
head = p1; /*让head指向p1节点,排序完成后,我们再把p1节点释放掉*/
for (endpt=NULL; endpt!=head; endpt=p) /*结合第6点理解*/
{
for (p=p1=head; p1->next->next!=endpt; p1=p1->next)
{
if (p1->next->num > p1->next->next->num) /*如果前面的节点键值比后面节点的键值大,则交换*/
{
p2 = p1->next->next; /*结合第1点理解*/
p1->next->next = p2->next; /*结合第2点理解*/
p2->next = p1->next; /*结合第3点理解*/
p1->next = p2; /*结合第4点理解*/
p = p1->next->next; /*结合第6点理解*/
}
}
}
p1 = head; /*把p1的信息去掉*/
head = head->next; /*让head指向排序后的第一个节点*/
free(p1); /*释放p1*/
p1 = NULL; /*p1置为NULL,保证不产生“野指针”,即地址不确定的指针变量*/
return head;
}