在编码的过程中遇到的链表倒序存储问题。苦学了一番仍然懵懂。记录一下大神的代码方便日后复习
#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
网友评论