- 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;
- }
- }
- }
转载于:https://my.oschina.net/u/1270794/blog/165004