OC簡單實現鍊錶

2021-07-17 04:50:33 字數 2716 閱讀 2347

學習之餘用oc寫了個鍊錶,由於之前一直寫c語言,所以用了兩種寫法實現,兩種都是類的方法實現不過實現方式不一樣

第一種是變相的結構體寫法,裡面有濃濃的c語言結構體的味道

先看一下第一種寫法

ps:乙個shnode類和一盒main

shnode.h:
#import @inte***ce shnode : nsobject

@property shnode *head;//鍊錶的頭,學懂了oc的類其實這個頭可以省略,不過現在為了便於理解就寫上了

@property shnode *lastnode;//鍊錶的當前的最後乙個結點,因為鍊錶採用的是尾插法,以前一直用的頭插法這次換個寫法

@property int data;//鍊錶中要存的資料,可以自定義多個

@property shnode *next;//指向下乙個結點

-(void)print;//列印鍊錶的方法

+(id)nodelist;//初始化鍊錶的工廠方法,這裡可以不用這個,只不過用了會方便一些,牽扯到設計模式就不多說了

@end

shnode.m:
#import "shnode.h"

@implementation shnode

/*
初始化頭
*/

-(instancetype)init

return self.lastnode;

}/*

往煉表中插入結點
*/

+(id)nodelist

/*

列印整個鍊錶
*/

-(void)print

}@end

main.m:
#import #import "shnode.h"

int main(int argc, const char * argv)

[head print];

clock_t end = clock();

unsigned long int timeuse = end - begin;//這裡是測試建立鍊錶耗費的時間

printf("\n\n%lu\n\n",timeuse);

printf("\n");

}return 0;

}

總結:這個類純粹是c語言中結構體的寫法下面來看下純類的寫法:

這個寫法分成兩個類,乙個鍊錶類乙個結點類

先看下結點類:

shnode.h
#import @inte***ce shnode : nsobject

@property int data;//結點中的資料

- (id)initwithdata:(int)data;//結點初始化

@end

shnode.m
#import "shnode.h"

@implementation shnode

- (instancetype)init

return self;

}- (id)initwithdata:(int)data

return self;

}@end

然後是鍊錶類; 

shlist.h
#import #import "shnode.h"

@inte***ce shlist : nsobject

@property shnode *head;//定義鍊錶的頭

@property shnode *hail;//定義鍊錶的尾巴

-(void)printlist;//列印鍊錶

+(id)listwithdata:(int)data;//工廠方法

@end

shlist.m
#import "shlist.h"

@implementation shlist

- (instancetype)initwithdata:(int)data

return self;

}+(id)listwithdata:(int)data

-(void)printlist

}@end

接下來就是main函式啦

#import #import "shlist.h"

int main(int argc, const char * argv)

[newlist printlist];

printf("\n");

}return 0;

}

以上就是所有的**,如有不對之處還望指

簡單鍊錶實現

今天元旦,不想工作。只想寫一寫自己想學習的東西。今天就寫了個鍊錶的單向鍊錶。標頭檔案chain.h ifndef chain define chain include include using namespace std templateclass chain templateclass chai...

鍊錶實現系列(一) 簡單鍊錶Java實現

簡單鍊錶的原理在這裡就不贅述了,推薦一篇比較不錯的部落格 鍊錶原理 需要實現的操作包括 在頭節點之前插入節點 在尾節點之後插入節點 刪除包含指定資料的節點 刪除尾節點 查詢包含指定資料的節點 獲取鍊錶的長度 輔助操作包括 清空鍊錶 判斷鍊錶是否為空。下面是簡單鍊錶的實現 注意 該鍊錶實現不適合用於儲...

c 鍊錶簡單實現

鍊錶 include using namespace std template struct node template class linklist public linklist node p new node head p p next null node push front const t...