[leetcode]206. Reverse Linked List反转链表

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 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9227151.html