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

来源:互联网 发布:软件服务器加防御 编辑:程序博客网 时间:2024/06/04 19:41

递归写法:

/*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;    }}


0 0
原创粉丝点击