1、题目描述
来源:牛客网
输入一个链表,反转链表后,输出新链表的表头。
2、解题思路
(1)递归法
确定递归出口:head == null 或者 head.next == null
(2)迭代法
定义一个dummyHead节点指向head节点,从左到右依次遍历链表,将链表分为反转后链表和未反转链表;
每次将未反转链表的第一个结点插入到dummyHead结点后面,重复迭代该操作,直到最后一个结点插入完毕后,dummyHead.next即为整个反转链表;
3、编码展示
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head){
// //1、递归法
// if(head == null || head.next == null){
// return head;
// }
// ListNode node = ReverseList(head.next);
// head.next.next = head;
// head.next = null;
// return node;
//2、迭代法
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
if(head == null || head.next == null){
return head;
}
ListNode f = dummyHead.next;
ListNode s = f.next;
while(s != null){
f.next = s.next;
s.next = dummyHead.next;
dummyHead.next = s;
s = f.next;
}
return dummyHead.next;
}
}