题目描述:
解法1:
这种方法是通过递归的方法复制一个新链表反转链表。首先新建一个有虚假头节点的新链表,然后递归去到旧链表的的最底部,把最底部的元素作为加入到新链表的底部。然后一层层递归,从底到顶,把元素加入到新链表底部。最后返回新链表的反转链表部分即可。
ListNode node = new ListNode();
public ListNode reverseList(ListNode head) {
ListNode cur = node;
bianli(head);
return cur.next;
}
public void bianli(ListNode head){
if(head == null) return ;
bianli(head.next);
node.next = new ListNode();
node.next.val = head.val;
node = node.next;
}
解法2:
这种方法是在原来链表的基础上修改。通过头插法,不断把后面的元素放在虚假头节点的后面。越后面的节点放的位置越前,越前面的节点放的位置越后。最后返回虚假头节点后面的链表即可。
public ListNode reverseList(ListNode head) {
ListNode pre = new ListNode(0);
pre.next = head;
while(head != null && head.next != null){
ListNode next = head.next;
head.next = head.next.next;
next.next = pre.next;
pre.next = next;
}
return pre.next;
}