剑指offer 15:反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

法一:迭代法

/*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
return null;
ListNode pre = null;
ListNode next = null; while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

法二:递归法

/*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
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;
}
}
上一篇:Android Fragment应用实战


下一篇:实现Sublime Text3中vue文件高亮显示的最有效的方法