反转链表,小技巧

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。


很经典的一个面试题, 考察下是否对链表熟悉, 代码量不大, 很适合面试的时候手写.

@interface Node : NSObject

+ (Node *)nodeWithArray:(NSArray *)array;

@property (nonatomic, assign) int data;
@property (nonatomic, strong) Node *next;

@end
------------

#import "Node.h"

@implementation Node

+ (Node *)nodeWithArray:(NSArray *)array {
    
    if (array.count==0) {
        return nil;
    }
    
    Node * first = [[Node alloc] init];
    first.data = [array.firstObject intValue];
    Node * preNode = first;
    for (int i = 1; i<array.count; i++) {
        Node * next = [[Node alloc] init];
        next.data = [array[i] intValue];
        preNode.next = next;
        preNode = next;
    }
    return first;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%d %@",self.data,self.next];
}


@end

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self reverseNode];
    
}


// 翻转链表
- (void)reverseNode {
    
//    NSArray * array = @[@(1)];
//    NSArray * array = nil;
    NSArray * array = @[@(1),@(2),@(3),@(4),@(5),@(6),@(7),@(8),@(9),@(10)];
    Node * head = [Node nodeWithArray:array];
    NSLog(@"翻转前 %@",head);
    
    Node * preNode = nil;
    Node * nextNode = nil;
    Node * currentNode = head;
    while (currentNode) {
        
        if (currentNode.next == nil) {
            head = currentNode;
        }
        nextNode = currentNode.next;
        currentNode.next = preNode;
        preNode = currentNode;
        currentNode = nextNode;
        
    }
    
    NSLog(@"翻转过后 %@",head);

    
}

上面是一个很标准的代码, 下面说下如何理解,在这个循环中,遵循着这么一个循环, 变量1=变量2; 变量2=变量3;变量3=变量4;变量4=变量1;上面的执行顺序可以微调,但是知道这个循环在写代码的时候会好很多,可以方便自查一下有没有遗漏.
这样一个完美循环之后,node的改成了执行前一个preNode, 然后工作节点向前移动一格, 相应的工作节点的preNode,nextNode也跟着向前移动一格.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值