链表:单链表反转链表代码
public class Test {
public static class ListNode {
Object value;
ListNode next;
ListNode(Object obj) {
value = obj;
}
@Override
public String toString() {
return "ListNode{" +
"value=" + value +
", next=" + next +
'}';
}
}
/**
* 反转链表
* 1->2->3->4->5
* 5->4->3->2->1
*
* @param head
* @return
*/
public static ListNode reverseList(ListNode head) {
if (head == null) {//规范的代码都会做防空判断
return null;
}
//1->2->3->4->5
//prev是永远的头节点,谁是头,谁就是prev
ListNode prev = head;
//current当前节点
ListNode current = head.next;
//next指向null代表链表尾节点
prev.next = null;
//null<-1 2->3->4->5
//prev=1,current=2
while (current != null) {//进入循环说明当前节点不为空,也就是有新的头节点需要反转
//第1次
/*
next=current.next--->3
current.next=prev--->1->null
prev=current--->2
null<-1<-2 3->4->5
current=next--->3
*/
//第2次
/*
next=current.next--->4
current.next=prev--->2->1->null
prev=current--->3
null<-1<-2<-3 4->5
current=next--->4
*/
//第3次
/*
next=current.next--->5
current.next=prev--->3->2->1->null
prev=current--->4
null<-1<-2<-3<-4 5
current=next--->5
*/
//第3次
/*
next=current.next--->null
current.next=prev--->4->3->2->1->null
prev=current--->5
null<-1<-2<-3<-4<-5
current=next--->null
*/
//第4次
/*
next=current.next--->null
跳出循环
*/
ListNode next = current.next;//临时变量存储当前节点的next
current.next = prev;//当前节点的next指向上一个头节点
prev = current;//重新指向之后,当前节点重新赋值头节点
current = next;//操作完成,赋值当前节点的下一个为当前节点
}
return prev;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = null;
System.out.println(node1);//ListNode{value=1, next=ListNode{value=2, next=ListNode{value=3, next=ListNode{value=4, next=ListNode{value=5, next=null}}}}}
System.out.println(node5);//ListNode{value=5, next=null}
reverseList(node1);
System.out.println(node5);//ListNode{value=5, next=ListNode{value=4, next=ListNode{value=3, next=ListNode{value=2, next=ListNode{value=1, next=null}}}}}
System.out.println(node1);//ListNode{value=1, next=null}
}
}