题目描述
输入一个链表,反转链表后,输出新链表的表头。
节点类如下:
public class Node {
public int value;
public Node next;
public Node(int data){
this.value = data;
}
}
反转单向链表的函数如下:
public Node reverseList(Node head){
if(head==null||head.next==null)//链表为空或者仅1个数直接返回
return head;
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
可以看到四行代码:
next = head.next; //1
head.next = pre; //2
pre = head; //3
head = next; //4
//第一步:next = head.next
将 head.next 赋值给 next 变量,也就是说 next 指向了节点2,先将节点2 保存起来。
//第二步:head.next = pre
将 pre 变量赋值给 head.next,即 节点1 指向了 null
//第三步:pre = head
将 head 赋值给了 pre,即 pre 指向节点1(保证了前面链表pre的头节点,后面的return pre就是返回了反转链表的头节点),将节点1 设为“上一个节点”
//第四步:head = next
将 next 赋值给 head,即 head 指向了节点2。将节点2 设为“头节点”
注明: 第三步:pre = head
将 head 赋值给了 pre,即 pre 指向节点head
(保证了前面链表pre的头节点,后面的return pre就是返回了反转链表的头节点),
帮助记忆:
代码
最终返回节点6
public class Solution {
static public ListNode ReverseList(ListNode head) {
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}return pre;
}
public static void main(String[] args) {
ListNode first=new ListNode(1);
ListNode second= new ListNode(2);
ListNode third=new ListNode(3);
ListNode forth= new ListNode(4);
ListNode fifth=new ListNode(5);
ListNode sixth= new ListNode(6);
first.next=second;
second.next=third;
third.next=forth;
forth.next=fifth;
fifth.next=sixth;
sixth.next=null;
ListNode rehead= ReverseList(first);
System.out.println(rehead.val);
}
}
示例:
转载自:https://blog.youkuaiyun.com/xyh269/article/details/70238501 写的非常详细。