首页 > 代码库 > ReverseLinkedList,ReverseLinkedList2,链表反转问题
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; }}
ReverseLinkedList,ReverseLinkedList2,链表反转问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。