您的位置:首页 > 其它

单链表翻转(递归与非递归)

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: