struct Node {
NSInteger data;
struct Node * next;
};
构建链表
- (struct Node *)constructList {
struct Node *head = NULL;
struct Node *cur = NULL;
for (NSInteger i=0; i<10; i++) {
//malloc()动态分配内存,用malloc分配内存的首地址
struct Node *node = malloc(sizeof(struct Node));
node->data = i;
if (head == NULL) {
head = node;
} else {
cur->next = node;
}
cur = node;
}
cur->next = NULL;
return head;
}
链表反转
- (void)testListReverse {
struct Node *p = [self constructList];
[self pirntList:p];
struct Node *newH = NULL;
while (p != NULL) {
struct Node *temp = p->next;
p->next = newH;
newH = p;
p = temp;
}
[self pirntList:newH];
}
- (void)pirntList:(struct Node *)head {
struct Node *temp = head;
NSLog(@"list is : ");
while (temp != NULL) {
if (temp) {
NSLog(@"%zd",temp->data);
temp = temp->next;
}
}
NSLog(@"\n");
}
网友评论