题目地址:
https://www.lintcode.com/problem/reverse-linked-list/description
翻转链表。只需注意用头插法转移node的时候要缓存一下下一个节点即可。代码如下:
public class Solution {
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode res = null;
while (head != null) {
ListNode tmp = head.next;
head.next = res;
res = head;
head = tmp;
}
return res;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。