我正在尝试实现一个链表,所以我有一个带有头文件的 Node 类,如下所示:
@interface Node : NSObject
@property(nonatomic,assign)int data;
@property(nonatomic,strong) Node *right;
@property(nonatomic,strong) Node *left;
@end
然后在另一个类中,我分配它们,然后调用一个方法来销毁给定值的所有出现:
Node *node0 = [[Node alloc]init];
Node *node1 = [[Node alloc]init];
Node *node2 = [[Node alloc]init];
Node *node3 = [[Node alloc]init];
Node *node4 = [[Node alloc]init];
node0.data = 1;
node1.data = 2;
node2.data = 5;
node3.data = 5;
node4.data = 3;
node0.right = node1;
node1.right = node2;
node2.right = node3;
node3.right = node4;
node4.right = NULL;
[self removeNodeWithValue:node0 value:5];
NSLog(@"node %d, %d, %d, %d, %d", node0.data, node1.data, node2.data, node3.data, node4.data);
这是方法本身:
-(void)removeNodeWithValue:(Node *)head value:(int)value
{
Node *toDelete;
while (head != NULL) {
if (head.data == value)
{
toDelete = head;
head = head.right;
toDelete = nil;
}
else
{
head = head.right;
}
}
}
==> 1, 2, 5, 5, 3
我知道我可以更改实例,因为如果我更改toDelete = nil
为toDelete.data = 4
,则输出为==> 1, 2, 4, 4, 3
。我的问题是,我如何销毁这些实例?谢谢。