题解 | #最长公共前缀#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//链表头为空,或者链表头的下一个为空
if(head == null || head.next == null){
return head;
}
//初始化前去节点,后驱节点
ListNode prev = null;
ListNode next = null;
//循环遍历,翻转链表,结束条件为当前节点是否为空节点
while(head != null){
//保存当前节点的后驱节点
next = head.next;
//更新反序的前驱结点
head.next = prev;
//更新前驱结点
prev = head;
//当前节点向后移动
head = next;
}
return prev;//返回链表反转后的头结点
}
}
查看6道真题和解析
