JAVA实现单向链表反转

来源:互联网 发布:servlet接收ajax json 编辑:程序博客网 时间:2024/06/05 10:30

《单向链表反转》
最近正在面试,求职Android应用方向的工作。基础知识还可以,但是算法,呵呵。做手机客户端的基本涉及算法不多,大多是架构设计,解耦,以及功能优化,UI,IO等。好了废话不多说。进入正题!

单向链表,你懂得。再此不多做解释。单向链表的反转,时间复杂度,空间复杂度低一些才是好算法吗。基本目前是做到了O(n).思路就是,声明三个引用pre,cur,tempNext,pre,cur分别指向第一个元素和第二个元素。tempNext存住第三个元素的引用。反转前两个,p2---->p1 (注意此时p2.next 已断开)需要原来指向第二个的引用指向第三个,既pre,cur移动到p2,p3 ,也就是pre 引用p2, cur引用p3 .跟第一次pre,cur分别指向p1,p2类似,如此往复下去.
需要注意的几点,
1 本身JAVA代码,需要注意Java是值传递还是引用传递。如果不注意的话,变量交换就会有问题。真的,亲!
2 各种临时变量的记录。不要绕晕了。同时也要注意上一点。 



上代码!!!自己写的,可运行。

</pre><pre name="code" class="java">package com.main;public class Main  {public static void main(String[] args) {String [] str={"11","2","45","67","23","44","55","89","74","10"};RevertListfromHead rl= new RevertListfromHead(str);}}package com.main;public class RevertListfromHead {public RevertListfromHead(String[] str) {MyLinkList mList = new MyLinkList(str);mList.printList(mList.head);        System.out.println("--------------------------");System.out.println("after revert list is ");mList.head=mList.revertLinkedList(mList.head);mList.printList(mList.head);}class MyLinkList {private Node head;private int mlength; public MyLinkList(String[] str) {head = new Node(str[0]);Node currentNode = head;for (int i = 1; i < str.length; i++) {currentNode.next = new Node(str[i]);currentNode = currentNode.next;}mlength = str.length;}public Node revertLinkedList(Node _head) {int sum=0;if (null == _head) {               return head;           }           Node pre = _head;           Node cur = _head.next;           Node tempnext;           while (null != cur) {           tempnext = cur.next;               cur.next=pre;               pre = cur;               cur = tempnext;              sum++;        }           //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head              head.next=null;           head = pre;                   return head;   }public void printList(Node _head) {Node tempNode = _head;while (tempNode != null) {System.out.println("current data is : " + tempNode.data);tempNode = tempNode.next;}}}static class Node {String data;Node next;public Node(String _data) {this.data = _data;}}}
	
				
		
原创粉丝点击