算法题之--《反转链表》

我们先从数组创建一个链表:

@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

链表反转

例如,我们要反转下面这个链表:


链表反转

只要重复2的动作一直到cur移动到最后的null节点,反转就完成了。
示例代码:

-(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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容