输入一个链表,反转链表后,输出链表的所有元素。

该题目来自剑指offer的面试题16.

输入一个链表,反转链表后,输出链表的所有元素。

思路如下:定义3个指针,分别指向当前结点,头一个结点,下一个结点,然后通过就地逆置即可。

代码就不太解释了。不理解的,可以参考剑指offer的书,上面写得很详细。

#include <stdio.h>
#include <string.h>

typedef struct Node{
    int num;
    struct Node *next;
}NodeHead,*Nodes;

void DeleteNode(Nodes head){
    
    if(head==NULL || head->next==NULL)
        return;
    Nodes pNode,pNext,pPre;
    //pPre = head;
    pNode = head->next;
    pPre = head;
    pPre->next = NULL;
    while(pNode->next!=NULL){
        pNext = pNode->next;
        pNode->next = pPre;
        pPre = pNode;
        pNode = pNext;
    }
    pNode->next = pPre;
    int i ;
    for(i = 0 ; i < 8 ;i++)
    {
        printf("%d",pNode->num);
        pNode = pNode->next;
    }
}

void main()
{
    
    Nodes head = NULL;
     head = (Nodes)malloc(sizeof(NodeHead));
    head->next = NULL;
    int i ;
    for(i = 8 ;i >= 1 ; i--){
        Nodes node = (Nodes)malloc(sizeof(NodeHead));
        node->num = i;
        node->next = head->next;
        head->next = node;
    }
    
    DeleteNode(head);
    
    /**
    Nodes tmp2;
    tmp2 = head->next;
    for(i = 0 ; i <3 ; i++){
        printf("%d",tmp2->num);
        tmp2 = tmp2->next;
    }
    **/
    
    
    return 0;
}
原文地址:https://www.cnblogs.com/CloudStrife/p/7275807.html