定義一個函數,輸入一個鏈表的頭結點,反轉該鏈表並輸出反轉後鏈表的頭結點。
很經典的一個面試題, 考察下是否對鏈表熟悉, 代碼量不大, 很適合面試的時候手寫.
@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也跟着向前移動一格.