题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

a)一个链表。

b)把i之前所有的结点的next都指向前一个结点,导致链表在结点i,j之间断裂。

        除了需要知道结点i本身之外,还需要i的前一个结点,因为需要把结点i的next指向结点h。同时还事先需要保存i的一个结点,以防止链表断开。因此相应地定义3个指针,分别指向当前遍历到的结点、它的前一个结点及后一个结点。

代码实现:

public class ListNode{
       int val;
       ListNode next;

       public ListNode(int val){
             this.val=val;
             this.next=null;
       }

       public String toString(){
             StringBuilder sb=new StringBuilder();
             sb.append("[");
             ListNode node=this;
             while(node.next!=null){
                   sb.append(node.val);
                   sb.append(", ");
                   node=node.next;
             }
             sb.append(node.val);
             sb.append("]");
             return sb.toString();
       }
}
public class Solution{
     public static ListNode reverseList(ListNode head){
             //反转之后结点
             ListNode pReversedHead=null;
             //当前结点
             ListNode pNode=head;
             //上一结点
             ListNode pPrev=null;
             while(pNode!=null){
                  //下一结点
                  ListNode pNext=pNode.next;
                  if(pNext==null){
                        pReversedHead=pNode;
                  }
                  pNode.next=pPrev;
                  pPrev=pNode;
                  pNode=pNext;
            }
     }

     public static void main(String[] args){
            ListNode node=new ListNode(1);
            ListNode node1=new ListNode(2);
            ListNode node2=new ListNode(3);
            ListNode node3=new ListNode(4);
            ListNode node4=new ListNode(5);
            ListNode node5=new ListNode(6);
            node.next=node1;
            node1.next=node2;
            node2.next=node3;
            node3.next=node4;
            node4.next=node5;
            System.out.println(node.toString());
            ListNode n=reverseList(node);
            System.out.println(n.toString());
     }
}

 

 posted on 2018-09-20 17:49  会飞的金鱼  阅读(100)  评论(0)    收藏  举报