数据结构--链表倒序存储

在编码的过程中遇到的链表倒序存储问题。苦学了一番仍然懵懂。记录一下大神的代码方便日后复习


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

typedef struct _Node
{
    _Node * next;
    int data;
}Node, * pNode;


void print_node(pNode head)
{
    pNode pIter=head;
    while(pIter)
    {
        printf("%d ", pIter->data);
        pIter=pIter->next;
    }
    printf("\n");
}

void invert(pNode head)
{
    pNode currentNode;  //指向当前节点
    pNode nextNode;     //指向下一个节点

    pNode tempHead=new Node;
    tempHead->next=head;

    //初始化,p指向链表第一个节点,head->next=NULL,即为单独的表头节点
    currentNode=tempHead->next;
    tempHead->next=NULL;
    
    printf("begin invert in func:\n");
    //倒插
    while(currentNode)
    {
        nextNode=currentNode->next;
        currentNode->next=tempHead->next;
        tempHead->next=currentNode;
        currentNode=nextNode;
        //调试用
        print_node(tempHead);
    }

    //需要实际的改变head所指向的地址(而非内容),即给head重新指向
    /*??&head=&(tempHead->next);??*/
    head=tempHead->next;
    printf("after invert in func:\n");
    print_node(head);
}


void main()
{
    pNode head=new Node;
    head->data=1;
    head->next=NULL;
    for(int i=4; i>1; i--)
    {
        pNode tempNode=new Node;
        tempNode->data=i;
        tempNode->next=head->next;
        head->next=tempNode;
    }
    printf("before invert in main:\n");
    print_node(head);
    invert(head);
    printf("after invert in main:\n");
    print_node(head);
}

代码出处:http://blog.csdn.net/xiaobai1593/article/details/6763861

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容