链表:反转链表

题目:实现反转单向和双向链表的函数

要求:如果链表长度为N,时间复杂度要求为 O(N),额外空间复杂度为 O(1)

变形:给定一个单向链表的头结点head,以及两个整数 from 和 to,在单向链表上把第 from 个节点到 to 个节点这一部分进行反转

 

 

 

 

 

分析:本题很简单,解题时注意做到不出错即可

主要掌握链表中反转链表的常规操作

 1 //单链表
 2 public class Node
 3 {
 4     public int data;
 5     public Node next;
 6 
 7     public Node(int data)
 8     {
 9         this.data = data;
10     }
11 }
12 
13 public Node reverse(Node head)
14 {
15     if(head == null || head.next == null)
16         return head;
17 
18     Node pre = null, next = null;
19 
20     while(head != null)
21     {
22         next = head.next;
23         head.next = pre;
24         pre = head;
25         head = next;
26     }
27 
28     return pre;
29 }

 

 1 //双链表
 2 public class DoubleNode
 3 {
 4     public int value;
 5     public DoubleNode next;
 6     public DoubleNode pre;
 7 
 8     public DoubleNode(int value)
 9     {
10         this.vaule = value;
11     }
12 }
13 
14 public DoubleNode reverse(DoubleNode head)
15 {
16     if(head == null || head.next == null)
17         return head;
18 
19     DoubleNode pre = null, next = null;
20 
21     while(head != null)
22     {
23         next = head.next;
24         head.next = pre;
25         head.pre = next;
26         pre = head;
27         head = next;
28     }
29 
30     return pre;
31 }

 

变形题目分析:

1. 首先需要判断 1<=from<=to<=N,如果不满足,则直接返回原来的头结点。

2. 找到第 from-1 个节点 fPre 和第 to+1 个节点 tPos。即发展前一个节点和后一个节点,把反转的部分先反转,然后正确连接 fPre 和 tPos。

3. 如果 fPre 为 null,则说明反转部分包含头节点,则返回新的头结点,也就是 to 位置的节点;如果不为null,返回旧的头节点。

 

 1 public Node reverse(Node head, int from, int to)
 2 {
 3     Node cur = head, fPre = null, tPos = null;
 4     int len = 0;
 5     while(cur != null)
 6     {
 7         len++;
 8         fPre = len == from - 1 ? cur : fPre;
 9         tPos = len == to + 1 ? cur : tPos;
10         cur = cur.next;
11     }
12 
13     if(from > to || from < 1 || to > len)
14         return head;
15 
16     Node pre = fPre == null ? head : fPre.next;
17     Node cur = pre.next;
18     pre.next = tPos;
19     Node next = null;
20     while(cur != tPos)
21     {
22         next = cur.next;
23         cur.next = pre;
24         pre = cur;
25         cur = next;
26     }
27     
28     if(fPre != null)
29     {
30         pre.next = fPre;
31         return head;
32     }
33 
34     return pre;
35 }

 

参考资料:程序员代码面试指南 IT名企算法与数据结构题目最优解,左程云

posted on 2016-08-03 09:43  Traveling_Light_CC  阅读(181)  评论(0编辑  收藏  举报

导航