📄 list.cpp
字号:
/* list.cpp - Robert Ollington - 1/8/05
(based upon Mike Cameron Jones' C implementation for KXA251)
This code illustrates the use of pointers to implement a linked list,
with a dummy header node. The last node's next will be NULL. (The use of
the dummy header node simplifies some of the code as it ensures that there
is always a node before every node containing an item, even the first
one.)
*/
#include <iostream.h>
#include <stdlib.h>
#include "list.h"
node::node(){
Student tempS;
data_item = tempS;
next = NULL;
}
node::node(Student n){
data_item = n;
next = NULL;
}
/* Function to create an empty list
(the void argument list indicates that it takes no arguments) */
list::list()
{
first = new node();
Student tempS;
first->data_item = tempS; /* superfluous initialisation */
first->next = NULL; /* necessary initialisation to indicate last node */
}
/* Function to return dynamically allocated memory in list */
list::~list()
{
/* Note that we don't really need to have the variable "current" here,
as we could just advance list itself if we preferred. (Some of the other
list functions also make use of an additional such variable.) */
node* current = first;
while(current)
{
node* to_free = current;
current = current->next;
//delete to_free;
/* Note that the simpler:
delete current;
current = current->next;
makes the mistake of using dynamically allocated memory after
it's been freed */
}
}
/* Function to insert n at front of list */
void list::insert_at_front(Student n)
{
node* new_node = new node(n);
new_node->next = first->next;
first->next = new_node;
}
/* Function to print list */
void list::print()
{
node* current = first->next;
while(current)
{
//printf("%d ", current->data_item);
cout<<current->data_item.getName()<<','<<current->data_item.getNumber();
cout<<endl;
current = current->next;
}
//printf("\n");
}
int list::getCount(){
int count = 0;
node* current;
current = first->next;
while(current!=NULL){
count++;
current = current->next;
}
return count;
}
/* Function to insert n in (non-decreasing) order in list - assuming list
items are already in (non-decreasing) order. */
/*void list::insert_in_order(int n)
{
node* before = first;
node* new_node = new node(n);
// Move along list until right place is found, looking for node after
which new node should go
while(before->next && (before->next->data_item < n))
{
before = before->next;
}
new_node->next = before->next;
before->next = new_node;
}*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -