算法2-链表反转

定义一个链表

@interface YKNode : NSObject
@property(nonatomic, copy) NSString *name;
@property(nonatomic, strong) YKNode *next;
@end
@implementation YKNode
@end

1.创建链表并打印

        //创建链表
        
        //头结点
        YKNode *headNode = [[YKNode alloc]init];
        headNode.name = @"头";

        //作为中间变量使用
        YKNode *_lastNode = headNode;
        for (int i = 0; i < 5; i ++)
        {
            YKNode *node = [[YKNode alloc]init];
            node.name = [NSString stringWithFormat:@"%d",i];
            
            _lastNode.next = node;
            
            _lastNode = node;
        }
        
    
        //打印链表
        _lastNode = headNode;
        NSLog(@"%@",_lastNode.name);
        while (_lastNode.next) {
            NSLog(@"%@",_lastNode.next.name);
            _lastNode = _lastNode.next;
        }   

打印结果
2019-02-12 18:09:27.224236+0800 demo[20450:3430929] 头
2019-02-12 18:09:27.225013+0800 demo[20450:3430929] 0
2019-02-12 18:09:27.225163+0800 demo[20450:3430929] 1
2019-02-12 18:09:27.225269+0800 demo[20450:3430929] 2
2019-02-12 18:09:27.225372+0800 demo[20450:3430929] 3
2019-02-12 18:09:27.225481+0800 demo[20450:3430929] 4

2.反转链表并打印

        //反转链表
        
        YKNode *currentNode = headNode;
        YKNode *newNode;
       
        while (currentNode.next) {
            YKNode *tmepNode = currentNode.next;
            currentNode.next = newNode;
            newNode = currentNode;
            currentNode = tmepNode;
        }
        
     
        //打印链表
        _lastNode = newNode;
        NSLog(@"%@",_lastNode.name);
        while (_lastNode.next) {
            NSLog(@"%@",_lastNode.next.name);
            _lastNode = _lastNode.next;
        }

打印结果:
2019-02-12 18:09:27.225727+0800 demo[20450:3430929] 3
2019-02-12 18:09:27.225821+0800 demo[20450:3430929] 2
2019-02-12 18:09:27.225931+0800 demo[20450:3430929] 1
2019-02-12 18:09:27.226021+0800 demo[20450:3430929] 0
2019-02-12 18:09:27.226133+0800 demo[20450:3430929] 头

你可能感兴趣的:(算法2-链表反转)