数据结构基础之--单链表反转

       数据结构是计算机学科的基础知识,也是程序员基础能力的体现。话不说将自己学习的一点积累分享给大家,因能力有限,如有错漏请大家批评指教。

说明: 三个指针搞定,p 工作指针, tmp指针保存p节点的下一个元 素, newh指针指向新链表头结点。
思路:每个工作周期内 p 的next指向newh,再使newh指向p,p指向tmp。当p为NULL时链表反转结束。
        目的:源A->B->C->D->E->F    结果: F->E->D->C->B->A      

        下面贴上我自己写的c++代码:

#include <iostream>

using namespace std;

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x = 0, struct ListNode *next = NULL) :
val(x), next(NULL) {}
};

class Solution {
public:
ListNode* ReverseList(void)
{
ListNode* newh = NULL;

      if (NULL == phead && NULL == phead->next)

       {

              pnewh = newh;

return newh;

       } 

for(ListNode* p = phead; p; )//p为工作指针
{
ListNode* tmp = p -> next;//temp保存下一个结点
p -> next = newh;
newh = p;
p = tmp;
}
pnewh = newh;
return newh;
}
public:
void init_list(int size)
{
phead = new(ListNode);

phead->val = 0;
phead->next = NULL;
ListNode *tmp = phead;

for(int i = 1; i < size; i++)
{
ListNode *p = new(ListNode);

p->val = i + 100;
p->next = NULL;
tmp->next = p;
tmp = tmp->next;
}
}

void list_print(void)
{
for(ListNode *p = phead; p != NULL; p = p->next)
{
cout << p->val << " ";
}
cout<<endl;
}

void rev_list_print(void)
{
for(ListNode *p = pnewh; p != NULL; p = p->next)
{
cout << p->val << " ";
}
cout<<endl;
}

public:
Solution(ListNode *p1 = NULL, ListNode *p2 = NULL) :
phead(p1), pnewh(p2){}
private:
ListNode *phead;
ListNode *pnewh;
};


void list_print(ListNode *phead)
{
for(ListNode *p = phead; p != NULL; p = p->next)
{
cout << p->val << " ";
}
cout<<endl;
}

int
main(int argc, char *argv[])
{
Solution list;

list.init_list(10);
list.list_print();

list.ReverseList();
list.rev_list_print();

return 0;
}

第一次写博客,不会排版,时间也很紧张,大家谅解,我会继续努力。

猜你喜欢

转载自blog.csdn.net/greenhandtemporarily/article/details/80373060