ReverseLinkedList,ReverseLinkedList2,链表反转问题
ReverseLinkedList:
public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) { return head; } ListNode pPre = new ListNode(0); pPre.next = head; ListNode curr = head; ListNode pNext = null; while(curr != null) { pNext = curr.next; curr.next = pPre; pPre = curr; curr = pNext; } head.next = null; return pPre; } }
ReverseLinkedList2:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
算法分析:其实就是反转链表加了个条件,先找到第m-1个元素,m个元素,第n+1个元素,反转后再连接起来。
public class ReverseLinkedList2 { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode temp1 = new ListNode(0); //新的头结点 ListNode newHead = temp1; temp1.next = head; //找到第m-1个节点 for(int i = 1; i < m; i ++) { temp1 = temp1.next; } ListNode temp2 = new ListNode(0); temp2.next = head; //找到第n+1个节点 for(int i = 0; i < n+1; i ++) { temp2 = temp2.next; } //第m个节点 ListNode temp = temp1.next; //反转第m到n节点 ListNode pPre = new ListNode(0); pPre.next = temp; ListNode pCurr = temp1.next; ListNode pNext = null; while(pCurr != temp2) { pNext = pCurr.next; pCurr.next = pPre; pPre = pCurr; pCurr = pNext; } temp1.next = pPre; temp.next = temp2; return newHead.next; } }