【发布时间】:2014-05-02 14:30:24
【问题描述】:
我正在 Objective C 中创建一个链接列表,它在大多数情况下都有效。唯一的问题是,当我打印列表中的项目时,它还会在打印每个项目后打印一个 0。
代码的输出是:
5 0 6 0 7
我试图弄清楚为什么会出现 0 以及如何阻止它。代码是:
Node 类头文件
@interface Node : NSObject {
NSInteger data;
}
-(id) initWith : (NSInteger) number;
@property (nonatomic) NSInteger getData;
@property (nonatomic, strong) Node *nextNode;
Node 类实现文件
-(id) initWith: (NSInteger)number {
self = [super init];
if (self) {
Node *node = [[Node alloc] init];
self.nextNode = node;
data = number;
}
return self;
}
-(id) init {
self = [super init];
if (self) {
// custom initialization
}
return self;
}
-(NSInteger)getData {
return data;
}
LinkedList 头文件
@interface LinkedList : NSObject {
NSInteger data;
}
-(id)initWith : (NSInteger) number;
-(void) insertInteger : (NSInteger) number;
-(void) printList;
LinkedList 实现文件
@implementation LinkedList
{
Node *head;
}
-(id)initWith:(NSInteger)number {
self = [super init];
if (self) {
if (head == nil) {
head = [[Node alloc] initWith:number];
}
}
return self;
}
-(id) init {
self = [super init];
if (self) {
// custom initialization
}
return self;
}
-(void) insertInteger:(NSInteger)number {
if (head == nil) {
head = [[Node alloc] initWith:number];
}
else {
// traverse to the end of the linked list
Node *currentNode = head;
while (currentNode.nextNode != nil) {
currentNode = currentNode.nextNode;
}
// add the item at the end of the list
Node *insertNode = [[Node alloc] initWith:number];
[currentNode setNextNode:insertNode];
}
}
-(void) printList {
if (head == nil) {
NSLog(@"List is empty");
}
else {
Node *currentNode = head;
while (currentNode.nextNode !=nil) {
NSLog(@"%tu", currentNode.getData);
currentNode = currentNode.nextNode;
}
}
}
主类文件
int main(int argc, const char * argv[])
{
LinkedList *list1 = [[LinkedList alloc] init];
[list1 insertInteger:5];
[list1 insertInteger:6];
[list1 insertInteger:7];
[list1 printList];
return 0;
}
【问题讨论】: