1. 思路
本方法为头插法,即建立一个新的头结点,将原链表按序插入到头结点后,新插入的节点的next域指向之前的结点。
1.1 图解
1.2 运行结果
2. 代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode reverseHead = new ListNode(0);
ListNode cur = head;
ListNode next = null;
while(cur != null){
next = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
return reverseHead.next;
}
}
单链表的代码在我上一篇博客中,并且其中也有反转单链表的方法,不过其是在链表内部的方法,返回值为void。