题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路一
使用头插法迭代进行反转
实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode newHead = new ListNode(-1);
while(head != null){
ListNode tmp = head.next;
head.next = newHead.next;
newHead.next = head;
head = tmp;
}
return newHead.next;
}
}
思路二
递归
实现
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode next = head.next;
head.next = null;
ListNode newHead = ReverseList(next);
next.next = head;
return newHead;
}