206. Reverse Linked List

Reverse a singly linked list.

我的答案:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode linkedList=new ListNode(0);
        linkedList.next=head;
        ListNode temp=new ListNode(0);
        if(linkedList.next!=null){
            temp.next=new ListNode(linkedList.next.val);
            while(linkedList.next.next!=null){
                linkedList.next=linkedList.next.next;
                ListNode tempNode=new ListNode(linkedList.next.val);
                tempNode.next=temp.next;
                temp.next=tempNode;
            }
        }else{return head;}
        return temp.next;
    }
}

改好之后的我的答案:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null){return head;}
        ListNode pre=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=pre;
            pre=head;
            head=temp; 
        }
        return pre;
    }
}

别人的答案:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head; ListNode prev = null; while(cur != null){ ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }

MA:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if(head!=None): newHead=ListNode(head.val) else: return head while(head.next!=None): head=head.next newNode=newHead newHead=ListNode(head.val) newHead.next=newNode return newHead

OA:
class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ previous = None while head: next_node = head.next head.next = previous previous = head head = next_node return previous

评论

此博客中的热门博文

225 Implement Stack using Queues

232. Implement Queue using Stacks

20. Valid Parentheses