Skip to content

Instantly share code, notes, and snippets.

@katsuobushiFPGA
Last active August 29, 2015 14:07
Show Gist options
  • Save katsuobushiFPGA/140ed6f593f55a16a475 to your computer and use it in GitHub Desktop.
Save katsuobushiFPGA/140ed6f593f55a16a475 to your computer and use it in GitHub Desktop.
//main.cpp
#include<stdio.h>
#include"SingleLinkedList.h"
int main(){
SingleLinkedList *s = new SingleLinkedList();
s->add(new Node(1));
s->remove(0);
printf("Node%d", *s->head);
// printf("Node%d", *s->head);
/*
for (int i = 0; i < 10; i++){
s->add(new Node(i));
}
for (int i = 0; i < s->m_length; i++){
printf("getAt(%d):%d\n", i, s->getAt(i));
}
s->remove(0);
s->remove(8);
for (int i = 0; i < s->m_length; i++){
printf("getAt(%d):%d\n", i, s->getAt(i));
}
*/
getchar();
return 0;
}
#include <stdio.h>
#include "Node.h"
class SingleLinkedList{
public:
SingleLinkedList();
~SingleLinkedList();
Node* FindLast();
void add(Node *n);
void remove(int index);
int getAt(int index);
public:
Node *head = NULL;
public:
int m_length=0;
};
SingleLinkedList::SingleLinkedList(){};
SingleLinkedList::~SingleLinkedList(){};
Node *SingleLinkedList::FindLast(){
Node *follow = head;
if (head == NULL){
return NULL;
}
else{
while (follow->next != NULL){
follow = follow->next;
}
return follow;
}
};
void SingleLinkedList::add(Node *n){
Node *p_last = FindLast();
if (head == NULL){
head = n;
m_length++;
}
else{
p_last->next = n;
m_length++;
}
}
void SingleLinkedList::remove(int index){
Node *p_follow=head;
Node *p_prev=nullptr;
if (index > m_length - 1){
return;
}
else{
if (head == NULL)return;
for (int i = 0; i < index; i++){
if (i==index - 1)p_prev = p_follow;
p_follow = p_follow -> next;
}
//head
if (p_prev == nullptr){
if (p_follow->next == nullptr){
head = NULL;
}
else{
head = p_follow->next;
}
delete p_follow;
}
//last
else if (p_follow->next == nullptr){
p_prev->next = nullptr;
delete p_follow;
}
else{
p_prev->next = p_follow->next;
delete p_follow;
}
m_length--;
}
}
int SingleLinkedList::getAt(int index){
Node *p_follow = head;
if (index > m_length - 1){
return NULL;
}
for (int i = 0; i < index;i++){
p_follow = p_follow->next;
}
return p_follow->value;
}
//Node.h
//int
class Node{
public:
Node();
Node(int val);
~Node();
void setValue(int val);
int getValue();
public:
int value;
Node *next;
Node *prev;
};
//実装部
Node::Node(){
value = NULL;
next = nullptr;
prev = nullptr;
};
Node::Node(int val){
value = val;
next = nullptr;
prev = nullptr;
};
Node::~Node(){};
void Node::setValue(int val){
value = val;
}
int Node::getValue(){
return value;
}
@katsuobushiFPGA
Copy link
Author

試行錯誤した結果

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment