在編碼的過程中遇到的鏈表倒序存儲(chǔ)問題。苦學(xué)了一番仍然懵懂果善。記錄一下大神的代碼方便日后復(fù)習(xí)
#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; //指向當(dāng)前節(jié)點(diǎn)
pNode nextNode; //指向下一個(gè)節(jié)點(diǎn)
pNode tempHead=new Node;
tempHead->next=head;
//初始化,p指向鏈表第一個(gè)節(jié)點(diǎn)都办,head->next=NULL,即為單獨(dú)的表頭節(jié)點(diǎn)
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;
//調(diào)試用
print_node(tempHead);
}
//需要實(shí)際的改變head所指向的地址(而非內(nèi)容)镜会,即給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