Reverse second half of linked list

非常简单,leetcode相似题:93,206,234,234中完全包括了这题的代码。

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode slow=head,fast=head;
        ListNode prev=null;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            prev=slow;
            slow=slow.next;
        }
        prev.next=reverse(slow);
        return head;
    }
    public ListNode reverse(ListNode head){
        ListNode prev=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }
}
  1. Reverse Linked List II
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode pre=dummy;
        ListNode cur=dummy.next;
        for(int i=1;i
  1. Reverse Linked List
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }
}
  1. Palindrome Linked List
public class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode middle=getMiddle(head);
        middle=reverse(middle);
        while(head!=null&&middle!=null){
            if(head.val!=middle.val) return false;
            head=head.next;
            middle=middle.next;
        }
        return true;
    }
    public ListNode getMiddle(ListNode head){
        ListNode slow=head,fast=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        return slow;
    }
    public ListNode reverse(ListNode head){
        ListNode prev=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }
}

你可能感兴趣的:(Reverse second half of linked list)