/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr){
return nullptr;
}
ListNode* res = nullptr;
while(head){
ListNode* temp = head->next;//先储存下一个节点
head->next = res;//把下一个节点指向res的nullptr指针
res = head;//res指针往head移动
head = temp;//head往后移
}
return res;
}
};
#include<iostream>
using namespace std;
struct ListNode{
int val;
struct ListNode *next;
ListNode():val(0),next(nullptr){};
ListNode(int x):val(x),next(nullptr){};
};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr){
return {};
}
ListNode* cur = nullptr;
while(pHead){
ListNode* temp = pHead->next;
pHead->next = cur;
cur = pHead;
pHead = temp;
}
while(cur){
cout << cur->val<<" ";
cur = cur->next;
}
return cur;
}
};
int main(){
int val;
ListNode* head = new ListNode(0);
ListNode* phead = head;
while(cin >> val){
ListNode* next_node = new ListNode(val);
head = head -> next = next_node;
}
phead = phead->next;
// while(phead){
// cout << phead->val<<" ";
// phead = phead->next;
// }
Solution s;
s.ReverseList(phead);
return 0;
}
go:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var cur *ListNode
for head != nil{
tmp := head.Next
head.Next = cur
cur = head
head = tmp
}
return cur
}