LC 206. Reverse Linked List

Posted kykai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 206. Reverse Linked List相关的知识,希望对你有一定的参考价值。

题目描述

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

参考答案

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode 
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) 
 7  * ;
 8  */
 9 class Solution 
10 public:
11     ListNode* reverseList(ListNode* head) 
12         ListNode* cur = NULL;
13         while(head)
14             ListNode * temp = head->next;
15             head -> next = cur;
16             cur = head;
17             head = temp;
18         
19         return cur;
20     
21 ;

补充说明

term 1:

temp = 2 3 4 5 null

head = 1 null = 1 2 3 4 5 null + null 

cur = 1 null 

head = 2 3 4 5 null 

term 2:

temp = 3 4 5 null

head = 2 1 null ( 2 3 4 5 null + 1 null)

cur = 2 1 null

head = 3 4 5 null

term 3:

temp = 4 5 null

head = 3 2 1 null = 3 4 5 null + 2 1 null

cur = 3 2 1 null

head = 4 5 null

......

以上是关于LC 206. Reverse Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LC 206. Reverse Linked List

206. Reverse Linked List

LeetCode 206 Reverse a singly linked list.

[刷题] LeetCode 206 Reverse Linked List

206. Reverse Linked List

Leetcode92. Reverse Linked List II && 206. Reverse Linked List