算法題之--《反轉(zhuǎn)鏈表》

我們先從數(shù)組創(chuàng)建一個鏈表:

@interface ListNode : NSObject

@property (nonatomic, assign) NSInteger key;
@property (nonatomic, strong) ListNode *next;

@end

@interface List : NSObject

-(instancetype)initFromArr:(NSArray *)arr;

@end
@implementation ListNode
@end


@interface List()
@property (nonatomic, strong) ListNode *head;
@end

@implementation List

-(instancetype)initFromArr:(NSArray *)arr {
    
    self = [super init];
    
    if (self) {
        
        ListNode *preNode;
        
        for (NSNumber *value in arr) {
            if (_head == nil) {
                _head = [[ListNode alloc] init];
                _head.key = [value integerValue];
                preNode = _head;
            } else {
                ListNode *newNode = [[ListNode alloc] init];
                newNode.key = [value integerValue];
                preNode.next = newNode;
                preNode = newNode;
            }
        }
    }
    return self;
}

-(NSString *)description {
    NSMutableString *result = [NSMutableString string];
    ListNode *currentNode = self.head;
    while (currentNode != nil) {
        [result appendString:[NSString stringWithFormat:@"%lu -> ", currentNode.key]];
        currentNode = currentNode.next;
    }
    [result appendString:@"null"];
    return [result copy];
}

@end

測試下:

    List *list = [[List alloc] initFromArr:@[@(1), @(2), @(3), @(4), @(5)]];
    NSLog(@"%@", list);
2019-09-03 17:38:26.028129+0800 Algorithm[1880:1129933] 1 -> 2 -> 3 -> 4 -> 5 -> null

鏈表反轉(zhuǎn)

例如,我們要反轉(zhuǎn)下面這個鏈表:


鏈表反轉(zhuǎn)

只要重復2的動作一直到cur移動到最后的null節(jié)點,反轉(zhuǎn)就完成了。
示例代碼:

-(void)reverse {
    
    ListNode *pre = nil;
    ListNode *cur = self.head;
    ListNode *next;
    
    while (cur != nil) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    
    self.head = pre;
}

測試:

    List *list = [[List alloc] initFromArr:@[@(1), @(2), @(3), @(4), @(5)]];
    [list reverse];
    NSLog(@"%@", list);
2019-09-03 17:40:46.705029+0800 Algorithm[1883:1130326] 5 -> 4 -> 3 -> 2 -> 1 -> null
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容