美文网首页
leetcode[206] Reverse Linked Lis

leetcode[206] Reverse Linked Lis

作者: 努力努力再努力_姜姜 | 来源:发表于2016-06-23 17:41 被阅读19次

    题目要求

    Reverse a singly linked list.

    实现思路

    通过头插法新建一个链表并将其返回

    代码

    /**
     * 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 node1= null;
            ListNode tmp = head;
            while(tmp!= null){
                if(node1 == null){
                    ListNode newNode = new ListNode(tmp.val);
                    node1 = newNode;
                    node1.next = null;
                    
                }else{
                    ListNode newNode = new ListNode(tmp.val);
                    newNode.next = node1;
                    node1 = newNode;
                }
                tmp = tmp.next;
            }
            return node1;
            
        }
    }
    

    相关文章

      网友评论

          本文标题:leetcode[206] Reverse Linked Lis

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