1. 程式人生 > >有關連結串列的程式設計(我的弱項)

有關連結串列的程式設計(我的弱項)

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

/*
public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
         if (head == null) {
            return null;
        }
        ListNode p1=head;
        ListNode p2=head;   //當前節點,並讓它指向傳進來的物件所在地址
        ListNode ppre=null; // 當前節點的前一個節點
        ListNode pnext=null;// 當前節點的後一個節點
        while (p2 != null){
            pnext=p2.next;  // 用pNext儲存原連結串列中節點指向的下一個節點
            if(pnext==null) // 如果當前節點的下一個節點為空,說明p2是最後一個節點
                p1=p2;      // 讓反轉頭節點指向當前連結串列尾節點
            p2.next=ppre;   // 核心,當前節點的下一個變成了上一個,完成了反轉
            ppre=p2;
            p2=pnext;       // 向後移動節點繼續進行反轉
        }
        return p1;
    }
}

 

輸入一個連結串列,按連結串列值從尾到頭的順序返回一個ArrayList。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> a=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         if (listNode != null) {
            printListFromTailToHead(listNode.next);  
            a.add(listNode.val);
        }
        return a;
    }
}

輸入一個連結串列,輸出該連結串列中倒數第k個結點。

/*
public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode p=head;
        ListNode p2=head;
        int h=0,s=0;
        while(p!=null){//記錄連結串列長度
            h++;
            p=p.next;
        }
        if(h<k)return null;
        while(p2!=null){
            if(s==h-k){//用總長度減去k及是倒數的位置
                return p2;
            }
            s++;
            p2=p2.next;
        }
        return p2;
    }
}