【LintCode-List】35. Reverse Linked List

lintcode 35. Reverse Linked List

url: https://www.lintcode.com/problem/reverse-linked-list/description

1、题目

Description

Reverse a linked list.
Have you met this question in a real interview?
Example

Example1:
For linked list 1->2->3, the reversed linked list is 3->2->1
Example2:
For linked list 1->2->3->4, the reversed linked list is 4->3->2->1
Challenge

Reverse it in-place and in one-pass

2、思路

递归实现or迭代

3、java代码实现

public class ReversedLinkedNode {

    public class RLNTest {
        public void test(){
            ListNode head = new ListNode(0);
            ListNode cur = head;
            for(int i = 1; i < 10; i++) {
                ListNode node = new ListNode(i);
                cur.next = node;
                cur = node;
            }
            Solution s = new Solution();
            head = s.reverse(head);
            System.out.println(head);
        }
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }


    public class Solution {
        /**
         * @param head: n
         * @return: The new head of reversed linked list.
         */
        public ListNode reverse(ListNode head) {
            if (head == null)
                return null;

            ListNode prev = head;
            ListNode cur = head.next;
            while (cur != null) {
                prev.next = cur.next;
                cur.next = head;
                head = cur;
                cur = prev.next;
            }
            return head;
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值