单链表反转的问题

IT保安 2014-11-06 09:24:13
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;

}


代码如上,一点也看不懂,请帮我做个注释好吗?一定要通俗易懂啊,我学习也不久,写的太笼统我还是看不懂啊!谢谢了!
...全文
222 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2014-11-07
  • 打赏
  • 举报
回复
我写了一个简单的,基本原理就是用一个倒置的链表来替代原来的链表
/*************************************************************************
    > 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;
}
IT保安 2014-11-06
  • 打赏
  • 举报
回复
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,因此整个链表完整了
我是这么理解的了,请问思路正确吗?
勤奋的小游侠 2014-11-06
  • 打赏
  • 举报
回复
你自己画图来看一下可能比较好。用文字表述很难说清楚
QIUSQJF 2014-11-06
  • 打赏
  • 举报
回复
拿出笔和纸,画图……再多的文字解释不如一张图的效果……

65,184

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧