单链表翻转(递归与非递归)
2017-02-05 22:22
344 查看
递归写法:
/*
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 nextNode = head.next; //记录head的next节点
ListNode newHead = reverseList(nextNode); //递归翻转
nextNode.next = head;
head.next = null;
return newHead;
}
}
非递归写法:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution
{
public ListNode ReverseList(ListNode head)
{
ListNode pre = null;
ListNode next = null;
while(head!=null)
{
next = head.next; //记录head的next节点
head.next = pre; //翻转
pre = head;
head = next; //pre、head依次向后移动一个节点,继续翻转
}
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 nextNode = head.next; //记录head的next节点
ListNode newHead = reverseList(nextNode); //递归翻转
nextNode.next = head;
head.next = null;
return newHead;
}
}
非递归写法:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution
{
public ListNode ReverseList(ListNode head)
{
ListNode pre = null;
ListNode next = null;
while(head!=null)
{
next = head.next; //记录head的next节点
head.next = pre; //翻转
pre = head;
head = next; //pre、head依次向后移动一个节点,继续翻转
}
return pre;
}
}
相关文章推荐
- 单链表递归反转和非递归翻转
- 单链表递归和非递归两种翻转方法(手写链表)
- 用递归和非递归的方法 逆置单链表
- 反转单链表 递归与非递归
- 翻转二叉树(递归与非递归)
- 链表面试题之合并有序的两个线性表-递归和非递归的方法
- 单链表倒置(递归与非递归)
- 剑指Offer面试题16反转链表(递归和非递归),面试题17合并两个排序的链表(递归)
- 边看边写(链表反转(递归和非递归))
- 翻转链表-迭代和递归双版本
- 合并两个有序链表 递归和非递归的形式
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 链表反转(使用递归和非递归两种方式)
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 用递归和非递归两种方法翻转一个链表
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 单链表反转(递归和非递归)
- 反转链表(递归与非递归)
- 单链表就地逆置递归与非递归的方法
- 链表的逆置(用到递归和非递归)