JAVA版 头插法
分享头插法的解法。
比如有链表
原链表 1->2->3 head = 1;
反转后 3->2->1 root为新链表的头节点
分三步:
① 把原链表中的2 (head,next) 先放在新链表的头节点的前面 ,即 2 -> root //head.next = root;
② 把原链表的的head放在root的位置 即 由 2 -> root 变成2 -> 1 //root = head;
③ 让原链表的head指针往下走, //head = temp; temp是专门保存 原链表中下一个节点的临时节点。
/*
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 root= null;
while(head != null){
ListNode temp = head.next; //临时节点用来保存原链表中下一个节点。
head.next = root; // ①
root= head;//②
head = temp;//③
}
return root;
}
}


京公网安备 11010502036488号