gpt4 book ai didi

ios - Objective-C 中的链表问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:05 24 4
gpt4 key购买 nike

我正在尝试向头部添加一个节点,但头部为零。知道发生了什么事吗?

I have this picture of the debug process.

[注意它是一个带有大小的链表的实现,不要让你迷惑!]

节点.h

//literally contains no other code and the .m file is empty, all I want
//is a pointer to the next object
@interface Node : NSObject
@property (nonatomic, weak, readwrite) Node *next;
@end

NList.m -- 省略.h 因为我觉得应该没问题

@interface NList()
@property (weak, nonatomic, readwrite) Node *head;
@property (nonatomic,readwrite) NSInteger size;
@property (nonatomic) NSInteger num_nodes;
@end

...


- (id) initWithSize:(NSInteger)size {
self = [super init];
if (self){
self.head = nil;
self.size = size;
self.num_nodes = 0;
}
return self;
}

- (void)add:(NSObject *)node {
Node *newNode = [[Node alloc] init];
if (self.head){
newNode.next = self.head;
self.head = newNode;
}
else{
self.head = newNode;
}
self.num_nodes++;
}

测试文件

- (void)testAdd
{
NList *testList = [[NList alloc] initWithSize:2];
NSObject *testNodeOne = @1;
[testList add:(testNodeOne)];
XCTAssertNotNil(testList.head);
NSObject *testNodeTwo = @3;

[testList add:testNodeTwo];
XCTAssertNotNil(testList.head);
//XCTAssertNotNil(testList.head.next);

}

最佳答案

为什么你的节点属性很弱?根据您在此处展示的内容,它们应该很坚固。列表本身应该保留根节点(头),列表中的每个节点都应该保留下一个节点,否则其他任何东西都不会保留这些对象。

此外,作为旁注,在查看您的属性时,我认为您在查看 readwritereadonly 时混淆了默认值。 readwrite 是默认值,不需要明确指定。 readonly 需要为任何不应该有修改器的属性明确指定。您的属性中似乎有此倒退。

关于ios - Objective-C 中的链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com