程序媛詹妮弗
终身学习

Reverse a singly linked list.

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

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

题意:

如题

 

思路:

 

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode reverseList(ListNode head) {
11             ListNode cur = head;
12             ListNode pre = null;
13         while(cur!= null){
14             ListNode temp = cur.next;     
15             cur.next = pre;
16             cur = temp;   
17         }      
18     }
19 }

 

posted on 2018-06-26 04:39  程序媛詹妮弗  阅读(137)  评论(0编辑  收藏  举报