1. 程式人生 > >輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。

輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。

public class Solution {

public ListNode ReverseList(ListNode head) {

   ListNode pre=null;
   
   ListNode next=null;
   //next的目的是每次從從左到右去掉一個節點
   while(head!=null){
       //每次向右移動
       next=head.next;
	   //head.nexe=pre 就相當於第k個節點的next指向前k-1節點(k-1個節點已經逆序好)
       head.next=pre;
	   //把逆序好的一部分賦值給pre,就是說pre在當前的數目下,是已經逆序好的
       pre=head;
	   //head等於每次去掉一個節點後的節點
       head=next;
	   
   }
    return pre;