您的位置:首页 > 其它

Q16:反转链表

2016-07-28 23:21 302 查看

public
class
Q16 {
   /**
    *
题目:反转链表
    *
题目说明:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
    *
注意:要注意空表的情况和只有一个结点的情况。
    *
思路:用三个指针分别指向三个相邻的变量值。前一个结点,当前结点和后一个结点。
    * 1)用当前结点now的后继指向当前结点的前驱;
    * 2)将pre指向当前结点
    * 3)将now指向下一个结点
    */
   public
static void
main(String[] args) {
      ListNode head = new ListNode();
      ListNode second = new ListNode();
      ListNode third = new ListNode();
      ListNode forth = new ListNode();
      head.nextNode = second;
      second.nextNode = third;
      third.nextNode = forth;
     
      head.data = 1;
      second.data = 2;
      third.data = 3;
      forth.data = 4;
     
      Q16 test = new Q16();
      ListNode result = test.ReverseList(head);
      System.out.println(result.data);
   }
   public
ListNodeReverseList(ListNode head){
      if(head ==
null){//对链表的合法性进行判断
         returnnull;
      }
      if(head.nextNode ==
null){//只有一个结点
         return head;
      }
      ListNode preNode = null;//pre指向原链表的当前结点的前驱结点
      ListNode nowNode = head;//now指向当前结点
      ListNode reveredHead =
null
;//反转链表的头结点
      while(nowNode.nextNode !=
null){
         ListNode next = nowNode.nextNode;//当前结点的后继结点
         if(next ==
null){
            reveredHead = next;//如果当前结点的后继结点的next为null,则当前结点的后继结点为反转链表后的头结点。
         }
         nowNode.nextNode = preNode;//1)a.nextNode=null;  2)b.nextNode=a;  ...
         preNode = nowNode;        
//1)preNode=a;            2)preNode=b;  ...
         nowNode = next;       
//1)nowNode=b;            2)nowNode=c;  ...
      }
      return nowNode;//返回反转后的链表的表头
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: