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

......

posted @ 2019-10-06 11:54  schaffen  阅读(22)  评论(0编辑  收藏