单链表的反转非递归算法

定义单链表的结点

typedef struct ListNode{
    int value;
    ListNode *next;
}ListNode;

我们采用的单链表是带头结点的。

需要遍历一遍链表,在遍历过程中,把遍历的节点一次插入到头部。在这个过程之后,第一个节点成了最后节点,因此要特殊处理,改其后继为NULL。

void Inversion(ListNode* head)
{
    if(head->next == NULL)
        return; //带头结点的单链表,当单链表为空时

    if(head->next->next == NULL)
        return; //只有一个结点

    ListNode* pre = head->next;
    ListNode* current = head->next->next; //或者 current = pre->next;
    while(current != NULL)
    {
        pre->next = current->next;
        current->next = head->next;
        head->next = current;
        current = pre->next; //curent移动到pre指向的下一个结点,循环继续进行单链表逆序
    }
}

测试代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    ListNode * head = (ListNode*)malloc(sizeof(ListNode));
    if(NULL == head)
        printf("malloc failed!
");

    ListNode* tmp = head;
    for(int i=1; i<=10; i++)
    {
        tmp->next = (ListNode*)malloc(sizeof(ListNode));
        tmp->next->value = i;
        tmp->next->next = NULL;
        tmp = tmp->next;
    }
    Inversion(head);
    tmp = head->next;

    while(1)
    {
        printf("tmp->value is %d
", tmp->value);
        if(tmp->next == NULL)
            break;
        tmp = tmp->next;
    }
    return 0;
}

参考:http://blog.csdn.net/kangroger/article/details/20237081

   http://blog.csdn.net/cyuyanenen/article/details/51473900

   http://blog.csdn.net/liujian20150808/article/details/50640979

原文地址:https://www.cnblogs.com/hpcpp/p/7053810.html