我想实现链表。我写了一个插入列表方法,打印方法,但反向打印有问题。主要问题是反向打印打印正常列表,而不是反转:
#include <iostream>
struct Node
{
int value;
struct Node *next;
};
struct List
{
struct Node *first, *last;
};
Node* node(int v)
{
Node *newNode = new Node();
newNode->value = v;
newNode->next = NULL;
return newNode;
}
List* list()
{
List *newList = new List();
newList->first = NULL;
newList->last = NULL;
return newList;
}
List* insert(List* s, Node* n)
{
if (s->last == NULL)
{
n->next = s->last;
s->last = n;
s->first = n;
return s;
}
s->last->next = n;
s->last = s->last->next;
return s;
}
void print(List* s)
{
Node *tmp = s->first;
while(tmp)
{
std::cout << tmp->value << ' ';
tmp = tmp->next;
}
std::cout << '\n';
}
void reverse_print(List* s)
{
if(s->first == NULL)
{
std::cout << '\n';
return;
}
else
{
std::cout << s->first->value << ' ';
s->first = s->first->next;
reverse_print(s);
}
}
int main(int argc, char *argv[])
{
List *myList2;
myList2 = list();
myList2 = insert(myList2, node(3));
myList2 = insert(myList2, node(5));
myList2 = insert(myList2, node(7));
myList2 = insert(myList2, node(9));
myList2 = insert(myList2, node(5));
myList2 = insert(myList2, node(34));
myList2 = insert(myList2, node(67));
print(myList2);
reverse_print(myList2);
}
答案 0 :(得分:4)
最好的方法是为打印节点设置单独的功能:
var label = UILabel()
var animator = UIDynamicAnimator()
//magenta
let color = UIColor(red: 229.0/255, green: 0.0/255, blue: 81.0/255, alpha: 1.0)
//größe
let size : CGFloat = 100
// set yPosition to be a random number between 20.0 and 220.0
let xPosition : CGFloat = CGFloat( arc4random_uniform(200))+20
// let bubble = UIView()
func bubble(let name: String){
//magenta
let color = UIColor(red: 229.0/255, green: 0.0/255, blue: 81.0/255, alpha: 1.0)
//size
let size : CGFloat = 100
// set yPosition to be a random number between 20.0 and 220.0
let xPosition : CGFloat = CGFloat( arc4random_uniform(200))+20
// let bubble = UIView()
label.frame = (CGRect(x: xPosition, y: 320, width: size, height: size))
label.layer.cornerRadius = label.frame.height/2
label.layer.masksToBounds = true
label.backgroundColor = color
label.textColor = UIColor.whiteColor()
label.text = name.uppercaseString
label.textAlignment = .Center
label.font = UIFont.boldSystemFontOfSize(12)
}
func gravity(){
let gravity = UIGravityBehavior(items: [label])
animator.addBehavior(gravity)
let collision = UICollisionBehavior(items: [label])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
let behavior = UIDynamicItemBehavior(items: [label])
behavior.elasticity = 0.35
animator.addBehavior(behavior)
}
答案 1 :(得分:2)
更改
else
{
std::cout << s->first->value << ' ';
s->first = s->first->next;
reverse_print(s);
}
到
else
{
reverse_print(s);
s->first = s->first->next;
std::cout << s->first->value << ' ';
}
应该可以帮助您有效地使用递归。