翻转链表_JAVA_中等
反转链表
http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
- 利用三个对象来反转链表的步骤
先用now保存当前头部
再使用head指向本次反转的头部
再将end(尾部)的下一位定位到下次反转的头部
最后进行本次反转
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
// 翻转
ListNode end = head, now;
while(end.next != null) {
// 保存当前头部
now = head;
// 将head移动到本次反转后的头部位置
head = end.next;
// 将尾部的next定位到下次反转头部位置
end.next = head.next;
// 反转
head.next = now;
}
return head;
}
}- 还可以使用栈来进行反转


