lintcode 35. Reverse Linked List
url: https://www.lintcode.com/problem/reverse-linked-list/description
1、题目
Description
Reverse a linked list.
Have you met this question in a real interview?
Example
Example1:
For linked list 1->2->3, the reversed linked list is 3->2->1
Example2:
For linked list 1->2->3->4, the reversed linked list is 4->3->2->1
Challenge
Reverse it in-place and in one-pass
2、思路
递归实现or迭代
3、java代码实现
public class ReversedLinkedNode {
public class RLNTest {
public void test(){
ListNode head = new ListNode(0);
ListNode cur = head;
for(int i = 1; i < 10; i++) {
ListNode node = new ListNode(i);
cur.next = node;
cur = node;
}
Solution s = new Solution();
head = s.reverse(head);
System.out.println(head);
}
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head == null)
return null;
ListNode prev = head;
ListNode cur = head.next;
while (cur != null) {
prev.next = cur.next;
cur.next = head;
head = cur;
cur = prev.next;
}
return head;
}
}
}