输入一个链表,反转链表后,输出链表的所有元素。
【题目分析】这个题目思路比较简单,思路代码中都有说明,需要注意的是,可以打印所有元素。
这个代码是自己写的
struct ListNode {
int val;//数据域
ListNode *next;//指针域
ListNode(int x) : val(x), next(NULL) {}//不用考虑Next指针为空,定义了构造函数,默认为空
};//构造函数
class Solution {
public: //链表指针头结点
ListNode* reverseList(ListNode* head) {
ListNode *new_head=NULL;//指向新链表的头指针
while(head){
ListNode *next=head->next;//备份head->next;
head->next=new_head;//更新head->next
new_head=head;//移动new_head
head=next;//遍历链表
}
return new_head;//返回新链表头结点
} //返回链表逆序后的头结点指针
};
这两段代码是Discuss中翻到的值得学习
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL) return NULL;//注意程序鲁棒性
ListNode* pNode=pHead;//当前指针
ListNode* pReverseHead=NULL;//新链表的头指针
ListNode* pPrev=NULL;//当前指针的前一个结点
while(pNode!=NULL){//当前结点不为空时才执行
ListNode* pNext=pNode->next;//链断开之前一定要保存断开位置后边的结点
if(pNext==NULL)//当pNext为空时,说明当前结点为尾节点
pReverseHead=pNode;
pNode->next=pPrev;//指针反转
pPrev=pNode;
pNode=pNext;
}
return pReverseHead;
}
}
//第二种方法是:递归方法 /*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//如果链表为空或者链表中只有一个元素
if(pHead==NULL||pHead->next==NULL) return pHead;
//先反转后面的链表,走到链表的末端结点
ListNode* pReverseNode=ReverseList(pHead->next);
//再将当前节点设置为后面节点的后续节点
pHead->next->next=pHead;
pHead->next=NULL;
return pReverseNode;
}
};
递归的方法其实是非常巧的,它利用递归走到链表的末端,然后再更新每一个node的next 值 ,实现链表的反转。而newhead 的值没有发生改变,为该链表的最后一个结点,所以,反转后,我们可以得到新链表的head。
注意关于链表问题的常见注意点的思考:
1、如果输入的头结点是 NULL,或者整个链表只有一个结点的时候
2、链表断裂的考虑
最后附上测试代码:
#include <bits/stdc++.h>
using namespace std;
/*Definition for singly-linked list.
解题思路:依次遍历链表结点,每遍历一个结点即逆置结点
*/
struct ListNode {
int val;//数据域
ListNode *next;//指针域
ListNode(int x) : val(x), next(NULL) {}//不用考虑Next指针为空,定义了构造函数,默认为空
};//构造函数
class Solution {
public: //链表指针头结点
ListNode* reverseList(ListNode* head) {
ListNode *new_head = NULL;//指向新链表的头指针
while (head){
ListNode *next = head->next;//备份head->next;
head->next = new_head;//更新head->next
new_head = head;//移动new_head
head = next;//遍历链表
}
return new_head;//返回新链表头结点
} //返回链表逆序后的头结点指针
};
int main(){
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution solve;
ListNode *head = &a;
cout<<"Before reverse:\n:"<<endl;
while (head){
printf("%d\n", head->val);
head = head->next;
}
head = solve.reverseList(&a);
printf("After reverse:\n");
while (head){
printf("%d\n", head->val);
head = head->next;
}
return 0;
}