Reverse Linked List
Reverse a singly linked list.code
click to show more hints.遞歸
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?it
非遞歸io
public class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; ListNode p=head,q=head.next,next=null; head.next=null; while(q!=null){ next=q.next; q.next=p; p=q; q=next; } return p; } }
2.遞歸class
public class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; ListNode tmp=reverseList(head.next); head.next.next=head; head.next=null; return tmp; } }
Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.cli
For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.sed
代碼List
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null||head.next==null) return head; ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=dummy,p=head; int count=1; while(count<m){ pre=p; p=p.next; count++; } ListNode pm=p; ListNode q=p.next,next=null; while(count<n){ next=q.next; q.next=p; p=q; q=next; count++; } ListNode pn=p; pre.next=pn; pm.next=q; return dummy.next; } }