ผลต่างระหว่างรุ่นของ "Adt lab/linked lists"
ไปยังการนำทาง
ไปยังการค้นหา
Jittat (คุย | มีส่วนร่วม) (→struct) |
Jittat (คุย | มีส่วนร่วม) |
||
แถว 26: | แถว 26: | ||
== Linked list class == | == Linked list class == | ||
+ | <source lang="cpp"> | ||
+ | typedef int valueType; | ||
+ | |||
+ | struct ListNode | ||
+ | { | ||
+ | valueType val; | ||
+ | ListNode* next; | ||
+ | |||
+ | ListNode(valueType val, ListNode* next=0) | ||
+ | : val(val), next(next) {} | ||
+ | }; | ||
+ | |||
+ | class LinkedList | ||
+ | { | ||
+ | private: | ||
+ | ListNode* header; | ||
+ | void free_list(); | ||
+ | |||
+ | public: | ||
+ | LinkedList(); | ||
+ | ~LinkedList(); | ||
+ | void print_list(); | ||
+ | void insert_front(valueType x); | ||
+ | }; | ||
+ | |||
+ | LinkedList::LinkedList() | ||
+ | { | ||
+ | header = new ListNode(0); | ||
+ | } | ||
+ | |||
+ | LinkedList::~LinkedList() | ||
+ | { | ||
+ | free_list(); | ||
+ | } | ||
+ | |||
+ | void LinkedList::print_list() | ||
+ | { | ||
+ | ListNode* node = header->next; | ||
+ | while(node != 0) { | ||
+ | cout << node->val << endl; | ||
+ | node = node->next; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | void LinkedList::insert_front(valueType x) | ||
+ | { | ||
+ | } | ||
+ | |||
+ | void LinkedList::free_list() | ||
+ | { | ||
+ | } | ||
+ | </source> |
รุ่นแก้ไขเมื่อ 15:58, 1 ตุลาคม 2558
- This is part of adt lab
List nodes
typedef
In C++, you can simply declare a new type based on known types using typedef.
typedef int valueType;
valueType x = 10;
We will declare new valueType so that our linked list code works fairly well with any types. We will eventually use template to make generic linked list.
struct
struct ListNode
{
valueType val;
ListNode* next;
ListNode(valueType val, ListNode* next=0)
: val(val), next(next) {}
};
Linked list class
typedef int valueType;
struct ListNode
{
valueType val;
ListNode* next;
ListNode(valueType val, ListNode* next=0)
: val(val), next(next) {}
};
class LinkedList
{
private:
ListNode* header;
void free_list();
public:
LinkedList();
~LinkedList();
void print_list();
void insert_front(valueType x);
};
LinkedList::LinkedList()
{
header = new ListNode(0);
}
LinkedList::~LinkedList()
{
free_list();
}
void LinkedList::print_list()
{
ListNode* node = header->next;
while(node != 0) {
cout << node->val << endl;
node = node->next;
}
}
void LinkedList::insert_front(valueType x)
{
}
void LinkedList::free_list()
{
}