题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ /** 思路:用三个指针对链表进行遍历,每访问一个节点就修改该节点的next指针, 用temp1表示当前节点的前一个节点,temp表示当前节点的下一个节点,head表示当前节点 temp = head.next; head.next = temp1; temp1 = head; head = temp; 当head.next为空时,表示到达最后一个节点,循环结束,修改head.next=temp1,返回head */ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null){ System.out.println("{}"); return head; }else{ ListNode temp = null;//表示当前节点的下一个节点 ListNode temp1 = null;//表示当前节点的上一个节点 while(head.next != null){//head表示当前节点 temp = head.next; head.next = temp1; temp1 = head; head = temp; } head.next = temp1; return head; } } }