鏈表的object-c語言實現鏈表的建立、插入、刪除、查找等功能(arc): #import <UIKit/UIKit.h> @interface List : NSObject//List爲鏈表接口名字 @property NSInteger value;//節點整造成員 @property List *next;//節點指針型成員 //create - (instancetype)init;//初始化鏈表 +(instancetype)createLikedList;//建立鏈表 -(void)insertBeforeList:(List *)Node inserbefore: (List *)NewNode;//在節點前插入節點 -(void)insertAfterList:(List *)NewNode;//在節點後插入節點 -(void)deleteList:(List *)Node;//刪除節點 -(List *)searchList:(int)values;//查詢節點 @end #import "List.h" @implementation List - (instancetype)init{ if (self = [super init]) {//初始化鏈表 self->_value = 0; self->_next = nil; } return self; } + (instancetype)createLikedList {//建立鏈表 List *L = [[List alloc] init]; return L; } -(void)insertBeforeList:(List *)Node inserbefore: (List *)NewNode{//向前插入節點 List *CosorNode = self; while (CosorNode.next != nil) { if (CosorNode.next.value == Node.value) {//根據節點的value進行查詢 NewNode.next = CosorNode.next; CosorNode.next = NewNode; break; }else { CosorNode = CosorNode.next; } } } -(void)insertAfterList:(List *)NewNode{//向後插入節點 List *CosorNode = self; while (CosorNode.next != nil) { CosorNode = CosorNode.next; } CosorNode.next =NewNode; NewNode.next = nil; } -(void)deleteList:(List *)Node{//刪除節點 List *CosorNode = self; while (CosorNode.next!=nil) { if (CosorNode.next.value == Node.value) { CosorNode.next = Node.next; break; }else{ CosorNode = CosorNode.next; } } } -(List *)searchList:(int)values{//查找節點 List *CosorNode = self; while (CosorNode.next!=nil) { if (CosorNode.next.value == values) { return CosorNode.next; break; }else{ CosorNode = CosorNode.next; } } return nil; } @end
隊列的object-c實現隊列的建立、入隊、出隊功能(arc): #import <Foundation/Foundation.h> @interface Queue : NSObject @property NSInteger value; @property Queue *next; -(instancetype)init; +(instancetype)createWithQueue; -(void)enqueue:(Queue *)Node; -(instancetype)outqueue; @end #import "Queue.h" @implementation Queue -(instancetype)init{//初始化頭結點 if (self = [super init]) { self->_value = 0; self->_next = nil; } return self; } +(instancetype)createWithQueue{ Queue *q = [[Queue alloc] init];//建立隊列 return q; } -(void)enqueue:(Queue *)Node {//入隊 Queue *q = self; while (q.next!=nil) {//循環找到隊列的最後一個節點(指向nil)。 q = q.next; } q.next = Node;//將尾節點指向入隊節點 Node.next = nil; } -(instancetype)outqueue{//出隊 Queue *q1;//做爲轉換的中間節點 Queue *q = self; if (q.next==nil) {//若是隊列只有一個則返回自己 return q; }else{//不然取頭結點後面的第一個節點做爲返回值 q1 = q.next; q.next = q.next.next; return q1; } } @end