反转链表,小技巧

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


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

@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也跟着向前移动一格.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章