leetcode | Reverse Linked List

来源:互联网 发布:软件集成商 编辑:程序博客网 时间:2024/06/06 00:00

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?

这是迭代的方式

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        ListNode nextNode = head.next;                  head.next = null;        while(nextNode!=null)        {   //1,2,3            ListNode nextNextNode = nextNode.next;            nextNode.next = head;//2->1            head = nextNode;// 2,1,3            nextNode = nextNextNode;                                }        return head;    }}

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        if (head == null) return null;         if (head.next == null) return head;         ListNode secondElem = head.next;          head.next = null;          ListNode reverseRest = reverseList(secondElem);          secondElem.next = head;          return reverseRest;      }}




0 0