美文网首页
iOS之【链表】

iOS之【链表】

作者: NJ_墨 | 来源:发表于2020-06-02 11:47 被阅读0次
    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");
    }
    

    相关文章

      网友评论

          本文标题:iOS之【链表】

          本文链接:https://www.haomeiwen.com/subject/fegvahtx.html