反转链表总结(JAVA实现)
反转链表做了好几次了,总记不住,可能太菜,趁头脑清醒记录一下
题目描述
输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//特殊情况 处理
//1.空链表
//2.一个结点 返回头结点
if(head==null) return null;
if(head.next==null) return head;
ListNode next = null;
ListNode pre = null;
//头结点不为空 为循环条件
while(head!=null){
//每次取出头结点的后一节点做标记,防止后边的代码破坏head结构无法继续遍历
next = head.next;
//1->2->3->4
/**
1.1->null 2->3->4
2.2->1->null 3->4
3.3->2->1->null 4
4.4->3->2->1->null null
将head作为中间变量 每次迭代更新pre的值 直到head为空结束遍历
*/
head.next = pre;
pre=head;
//将标记重新赋值给头结点
head = next;
}
return pre;
}
}