赞
踩
给定链表L0->L1->L2…Ln-1>Ln,把链表重新排序为L0->Ln->L1->Ln-1>L2->Ln-2…
要求:1.在原链表结点上排序,即不能申请新结点
2.只能修改next域,不能修改数据域
public class Sort { /** * 方法功能:找出链表的中间结点,并从中间断成两段 * 输入参数:链表的头结点 * 返回值:链表的中间结点 */ // 1.slow走一步,fast走两步 public static Node findMiddleNode(Node head){ if(head == null || head.next == null){ return head; } Node slow = head; Node fast = head; Node slowPre = head; // 要想走两步 while(fast != null && fast.next != null){ slowPre = slow; slow = slow.next; fast = fast.next.next; } slowPre.next = null; return slow; } /** * 方法功能:对不带虚假结点的单链表进行翻转 * 输入参数:链表的头结点 */ public static Node reverseNode(Node head){ if(head == null || head.next == null){ return head; } Node pre = null; Node nex = null; // null head nex , head和nex不需要考虑什么关系 while(head != null){ nex = head.next; head.next = pre; pre = head; head = nex; } return pre; } /** * 方法功能: 将两部分链表连接起来 * 输入参数: 链表的假头结点 */ public static void reorder(Node head){ if(head == null || head.next == null){ return; } // 前半部分第一个链表结点 Node cur1 = head.next; // 后半部分逆序的第一个链表结点 Node mid = findMiddleNode(head.next); Node cur2 = reverseNode(mid); Node tmp = null; while(cur1.next != null){ tmp = cur1.next; cur1.next = cur2; // 这里面只有cur1结点没用 cur1 = tmp; tmp = cur2.next; cur2.next = cur1; cur2 = tmp; } cur1.next = cur2; } public static void main(String[] args) { // 假的头结点 Node head = new Node(-1); Node cur = head; Node tmp = null; for(int i = 1; i < 8; i++){ tmp = new Node(i); cur.next = tmp; cur = tmp; } System.out.println("排序前为:"); for(cur = head.next; cur != null; cur = cur.next){ System.out.print(cur.data + " "); } System.out.println("\n --------------------------------------------"); System.out.println("排序后为:"); Sort.reorder(head); for(cur = head.next; cur != null; cur = cur.next){ System.out.print(cur.data + " "); } } }
查找、逆序、合并的时间复杂度为O(n),n为链表的长度,空间复杂度为O(1)
1.因为是单链表,所以只能往后移动,不能往前移动
2.所以找到中间结点,并且对后半部分进行逆序,然后合并前后两半部分。
1.翻转链表
方法一:创建虚假链表头
class Node{ int data; Node next = null; public Node(int data){ this.data = data; } } public class LinkedListSort { public static Node reverseOrder(Node head){ if(head == null || head.next == null){ return head; } // 创建一个假链表头,并指向head Node fakeNode = new Node(0); fakeNode.next = head; Node pre = head; Node cur = head.next; Node tmp1 = null; while(cur != null){ pre.next = cur.next; tmp1 = fakeNode.next; fakeNode.next = cur; cur.next = tmp1; // 经过上次交换后,cur和pre已经交换位置 cur = pre.next; } return fakeNode.next; } public static void main(String[] args) { Node head = new Node(1); Node fake = head; for(int i = 2; i < 7; i++){ Node tmp = new Node(i); fake.next = tmp; fake = fake.next; } fake = LinkedListSort.reverseOrder(head); while(fake != null){ System.out.print(fake.data + " "); fake = fake.next; } } }
方法2:不带,就是
添加链接描述
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。