题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
代码:
package leetCode;
import leetCode.Nineteen.ListNode;
/**
* 2018.7.23
* 反转链表
* 思路1:感觉可以先扫描一遍链表将值存到一个数组,在循环数组得出一个反转链表
* 思路2:感觉可以在扫描的同时以从链表头的方式插入结点完成链表反转
* 进阶思路:递归或迭代
* @author dhc
*
*/
public class TwoHundredAndSix {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
//采用思路2(当用注释的re是,是36ms,后来发现并不用这个re直接用head就行,直接0.5ms,有毒)
public static ListNode reverseList(ListNode head) {
if(head == null) {
return null;
}
//ListNode re = head;
ListNode loopNode = head.next;
head.next = null;
while(loopNode != null) {
ListNode tem = head;
head = loopNode;
loopNode = loopNode.next;
head.next = tem;
}
return head;
}
//采用递归方法(大佬答案,不是很好理解的样子)
public static ListNode reverseList1(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode sub = reverseList(head.next);
//让后面一个结点指向前一个结点,递归的话是从最后一个结点开始,一直到最开始的结点
head.next.next = head;
//如果不只为空的话,head.next==head.next.next,而head.next.next=head,最后形成一个环
head.next = null;
return sub;
}
public static void main(String[] args) {
ListNode head = new TwoHundredAndSix().new ListNode(1);
ListNode node1 = new TwoHundredAndSix().new ListNode(2);
ListNode node2 = new TwoHundredAndSix().new ListNode(3);
ListNode node3 = new TwoHundredAndSix().new ListNode(4);
ListNode node4 = new TwoHundredAndSix().new ListNode(5);
head.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
ListNode re = reverseList1(head);
while(re!=null) {
if(re.next == null) {
System.out.print(re.val);
}else {
System.out.print(re.val+"->");
}
re = re.next;
}
}
}