单链表逆序

2019-11-14  本文已影响0人  andy_tu

1.创建链表结构

typedef struct NODE{
    int value;
    struct NODE *pNext;
}Node;

2.新建节点

Node *createNode(int value)
{
    Node *p = malloc(sizeof(Node));
    
    p->value = value;
    
    return p;
}

3.打印函数

void printNodeInfo(Node *head)
{
    Node *pCur = head;
    while (pCur) {
        
        NSLog(@"当前节点值:%d", pCur->value);
        pCur = pCur->pNext;
    }
}

4.main函数实现

//链表逆序
- (void)LBNX
{
    Node *pHead = createNode(10);
    
    Node *p1 = createNode(20);
    pHead->pNext = p1;
    
    Node *p2 = createNode(30);
    p1->pNext = p2;
    
    Node *p3 = createNode(40);
    p2->pNext = p3;
    
    Node *p4 = createNode(50);
    p3->pNext = p4;
    
    Node *p5 = createNode(60);
    p4->pNext = p5;
    
    p5->pNext = NULL;
    
    
    printNodeInfo(pHead);
    
    Node *cur = NULL;
    Node *cur1 = NULL;
    Node *cur2 = NULL;
    cur = pHead;
    cur1 = cur->pNext;
    cur2 = cur1->pNext;
    cur->pNext = NULL;
    while (cur && cur1) {
        cur1->pNext = cur;
        cur = cur1;

        if (cur2 == NULL)
            break;

        cur1 = cur2;
        cur2 = cur2->pNext;
        
    }
    
    pHead = cur;
    
    printNodeInfo(pHead);
}

5.打印结果

2019-11-14 20:31:44.959604+0800 逆波兰数[1463:62294] 当前节点值:10
2019-11-14 20:31:44.959726+0800 逆波兰数[1463:62294] 当前节点值:20
2019-11-14 20:31:44.959837+0800 逆波兰数[1463:62294] 当前节点值:30
2019-11-14 20:31:44.959943+0800 逆波兰数[1463:62294] 当前节点值:40
2019-11-14 20:31:44.960042+0800 逆波兰数[1463:62294] 当前节点值:50
2019-11-14 20:31:44.960143+0800 逆波兰数[1463:62294] 当前节点值:60
2019-11-14 20:32:29.903751+0800 逆波兰数[1463:62294] 当前节点值:60
2019-11-14 20:32:29.903971+0800 逆波兰数[1463:62294] 当前节点值:50
2019-11-14 20:32:29.904118+0800 逆波兰数[1463:62294] 当前节点值:40
2019-11-14 20:32:29.904260+0800 逆波兰数[1463:62294] 当前节点值:30
2019-11-14 20:32:29.904392+0800 逆波兰数[1463:62294] 当前节点值:20
2019-11-14 20:32:29.904517+0800 逆波兰数[1463:62294] 当前节点值:10
上一篇 下一篇

猜你喜欢

热点阅读