美文网首页
206. Reverse Linked List

206. Reverse Linked List

作者: evil_ice | 来源:发表于2016-12-27 20:52 被阅读10次

题目206. Reverse Linked List

Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

1,递归
 public ListNode reverseList(ListNode head) {
        ListNode tempHead = new ListNode(1);
        ListNode node = head;
        reverse(tempHead,node);
        return tempHead.next;
     }
     
     private void reverse(ListNode head, ListNode node){
         if(node == null){
             return;
         }
         ListNode tempNode = node.next;
         node.next = head.next;
         head.next = node;
         reverse(head,tempNode);
     }
2,非递归
public ListNode reverseList(ListNode head) {
        ListNode tempHead = new ListNode(1);
        ListNode node = head;
        ListNode tempNode = null;
        while(node != null){
            tempNode = node.next;
            node.next = tempHead.next;
            tempHead.next = node;
            node = tempNode;
        }
        return tempHead.next;
    }

相关文章

网友评论

      本文标题:206. Reverse Linked List

      本文链接:https://www.haomeiwen.com/subject/jupevttx.html