链表反转I
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head==null||head.next==null){ return head; } ListNode pre=head; ListNode current=head.next; head.next=null; while(current!=null){ ListNode next=current.next; current.next=pre; pre=current; current=next; } return pre; } }
链表反转II(从m到n位置)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { //第一步首先要做校验 if(head==null||m>=n){ return head; } //第二步 增加一个头节点节点,对头节点节点进行进行处理处理 ListNode newHead=new ListNode(-1); newHead.next=head; head=newHead; //第三步 循环先找到找到M个节点 for(int i=1;i<m;i++){ head=head.next; } //第四步 定义四个指针 ListNode preM=head; ListNode mNode=head.next; ListNode nNode=mNode; ListNode postN=nNode.next; //第五步 反转从M的位置到N的位置 for(int j=m;j<n;j++){ ListNode next=postN.next; postN.next=nNode; nNode=postN; postN=next; } //最后一步 preM.next=nNode; mNode.next=postN; return newHead.next; } }