65,184
社区成员




void List<T>::Invert()
{
ListNode<T>* p = first,*q = 0;
while(p)
{
ListNode<T>* r = q; q = p;//r=最后一个结点,q=第一个结点,p=第一个结点
p = p->link;//p此时为第一个后面的结点
q->link = r;//
}
first = q;
}
/*************************************************************************
> File Name: inversion.c
> Author: Jukay
> Mail: hellojukay@gmail.com
> Created Time: 2014年11月07日 星期五 19时32分23秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
struct node;
struct node
{
char date;
struct node * next;
};
struct node * Create(char ch)
{
struct node *head = (struct node *)malloc(sizeof(struct node));
head -> date = ch;
head ->next =NULL;
return head;
}
//尾插入
void insert1(struct node *head, char ch)
{
for(;head ->next != NULL; )
head = head ->next;
struct node *p = (struct node *)malloc(sizeof(struct node));
p ->date = ch;
p ->next = NULL;
head ->next = p;
}
//头插入
void insert2(struct node **head, char ch)
{
struct node *p;
p = (struct node *)malloc(sizeof(struct node));
p ->date =ch;
p ->next = *head;
*head = p;
}
void destroy(struct node *head)
{
struct node *tmp;
for(;head != NULL; )
{
tmp = head ->next;
free(head);
head = tmp;
}
}
void print(struct node *head)
{
do
{
printf("%c",head ->date);
head = head ->next;
}while(head != NULL);
}
//采用头插入发倒置链表
void reverse(struct node **head)
{
struct node *p = *head;
struct node * tmp = *head;
for(; p != NULL; p = p ->next)
{
insert2(head, p ->date);
}
destroy(tmp);
}
int main()
{
struct node *head;
head = Create('h');
insert1(head, 'e');
insert1(head, 'l');
insert1(head, 'l');
insert1(head, 'o');
print(head);
printf("\n");
reverse(&head);
print(head);
destroy(head);
return 0;
}
void List<T>::Invert()
{
ListNode<T>* p = first,*q = 0;
while(p)
{
ListNode<T>* r = q; //起一个定义结点作用,下面3步每一循环都生成1个新的结点,
//r将他们保存,最后的效果就是r为一个结点,
//其link域指向在每一步的循环中所定义的r
q = p;//用q保存当前p的结点
p = p->link;//然后将p设置为p后面的结点,这样下一个循环就是用p后面的结点了
q->link = r;//q也就是保存的p的结点,将他的链接域指向下一个结点
}
//假设有n次循环,最后生成的r1一路指向r2...rn
first = q;//最终的r0在这里,因为将p保存给q后,p再指向下一个就为0,
//虽然q正确的将链接域指向了r,但是循环退出,第一个结点r0实际未定义
//因此在这里将q给first,因此整个链表完整了
我是这么理解的了,请问思路正确吗?