No.206 Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路与想法:
Every time we need to save the pointer of the next node then we can change the pointer of the linked list to achieve the goal of reversing this list. The important thing is to draw the whole process on paper so that we can solve it easily.
2017.6.1
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode nextNode = head.next;
head.next = newHead;
newHead = head;
head = nextNode;
}
return newHead;
}
}
Time Complexity:
O(n)