将链表中的特定位置进行反转,依次历遍要反转的每一个节点然后把其添加到第一个。
public ListNode reverseBetween(ListNode head, int m, int n) {
if(n-m==0)return head;
ListNode h = new ListNode(0);
h.next=head;
ListNode p=h,q,r;
for(int i=1;i<m;i++){
p=p.next;
}
q=p.next;
r=q.next;
for(int i=0;i<n-m;i++){
q.next=r.next;
r.next=p.next;
p.next=r;
r=q.next;
}
return h.next;
}
Update 2015/08/23: 上面的解法思路正确但是需要定义一个空的头结点,下面的做法不用新建结点,下面的答案是I的
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if(head==null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(true){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}
return p2;
}
}