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<m;i++){
            cur=cur.next;
            pre=pre.next;
        }
        for(int i=0;i<n-m;i++){
            ListNode temp=cur.next;
            cur.next=temp.next;
            temp.next=pre.next;
            pre.next=temp;
        }
        return dummy.next;
    }
}
  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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容