List-Reverse List

来源:互联网 发布:java游戏开发工程师 编辑:程序博客网 时间:2024/06/06 01:08

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; } * } *///iterativeclass Solution {    public ListNode reverseList(ListNode head) {        ListNode pre = null;        while(head != null){            ListNode temp = head.next;            head.next = pre;            pre = head;            head = temp;        }        return pre;    }}//recursiveclass Solution {    public ListNode reverseList(ListNode head) {       return helper(head,null);    }    public ListNode helper(ListNode head,ListNode res){        if(head == null) return res;        ListNode next = head.next;        head.next = res;        return helper(next,head);    }}
92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } *///因为头结点不确定,所以使用dummpy Nodeclass Solution {    public ListNode reverseBetween(ListNode head, int m, int n) {        if(head == null || m > n) return head;        ListNode dummpy = new ListNode(0);        dummpy.next = head;        head = dummpy;        //首先找到m的前一个点        for(int i = 1; i < m; i++){            if(head == null) return null;            head = head.next;        }        ListNode premNode = head;        ListNode mNode = head.next;        ListNode nNode = mNode,postnNode = mNode.next;        // reverse指定范围的链表        //走n-m-1步,因为是从m位置开始的        for(int i = m; i < n; i++){            if(postnNode == null) return null;            ListNode temp = postnNode.next;            postnNode.next = nNode;            nNode = postnNode;            postnNode = temp;        }        //首位连接逆转之后的链表        mNode.next = postnNode;        premNode.next = nNode;;        return dummpy.next;            }}



原创粉丝点击