码迷,mamicode.com
首页 > 其他好文 > 详细

LC 206. Reverse Linked List

时间:2019-10-06 13:46:52      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:tput   nbsp   ext   public   input   temp   val   ati   NPU   

题目描述

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

标签:tput   nbsp   ext   public   input   temp   val   ati   NPU   

原文地址:https://www.cnblogs.com/kykai/p/11626906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!