[链表]

来源:互联网 发布:mac怎么下载视频 编辑:程序博客网 时间:2024/05/21 10:11
题目:
给定一个单向链表的头结点head,以及两个整数from和to,在单向链表上把
第from个节点到第to个节点这一部分进行反转
要求:
1、如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)

2、如果不满足1<=from<=to<=N,则不用调整


public Node reversePart(Node head,int form, int to){int len = 0;Node node1 = head;Node fPre = null;Node tPos = null;while(Node1 != null){len ++;fPre = len == from -1 ? node1 : fPre;tPos = len == to + 1 ? node1 : tPos;node1 = node1.next;}if(from > to || from < 1 || to > len){return head;}node1 - fPre == null ? head:fPre.next;Node node2 = node1.next;node1.next = tPos;Node next = null;while(node2 != tPos){next = node2.next;node2.next = node1;node1 = node2;node2 = next;}if (tPre != null){fPre.next = node1;return head;}return node1;}


原创粉丝点击