非常簡單胧卤,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;
}
}
- 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;
}
}
- 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;
}
}
- 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;
}
}