1. 程式人生 > 實用技巧 >【Java資料結構】帶頭節點單鏈表的反轉,從尾到頭輸出,輸出倒數第k個節點

【Java資料結構】帶頭節點單鏈表的反轉,從尾到頭輸出,輸出倒數第k個節點

Java單鏈表的三個面試題:

1、將單鏈表反轉

2、從尾到頭輸出單鏈表

3、輸出單鏈表的倒數第k個節點

 1 import java.util.Stack;
 2 
 3 /**
 4  * @author ZhiYi Li
 5  * @create 2020/8/25 20:45
 6  */
 7 public class SingleLinkedTest {
 8     //問題1:查詢單鏈表中倒數第k個節點
 9     //普通思路,先計算連結串列長度,然後用長度減去k得到順序數的位置
10     //更裝逼的思路,快慢指標思路,定義一個rear=1,定義一個front為k
11     //,先讓front先走k個單位,之後front和rear同步增加,當front走到尾部時,rear就是在倒數k個的位置上
12 public static HeroNode getReciprocalK(HeroNode head,int k){ 13 if(head.next == null){ 14 return null; 15 } 16 HeroNode front = head; 17 HeroNode rear = head; 18 int i; 19 for (i = 0; i < k&&front!=null; i++) { 20 front = front.next;
21 } 22 if(i<k){ 23 return null; 24 } 25 while (front!=null){ 26 front = front.next; 27 rear = rear.next; 28 } 29 return rear; 30 } 31 //問題二:反轉單鏈表(頭插法) 32 public static void reverseNode(HeroNode head){ 33
if(head.next == null||head.next.next==null){ 34 return; 35 } 36 HeroNode temp = new HeroNode(0,"");//新頭節點 37 HeroNode temp2 = head.next; 38 HeroNode temp3; 39 while (temp2!=null){ 40 temp3 = temp2.next; 41 temp2.next = temp.next; 42 temp.next = temp2; 43 temp2 = temp3; 44 } 45 head.next = temp.next; 46 } 47 //問題三:從尾到頭列印單鏈表 48 public static void printRearToFront(HeroNode head){ 49 //方式一:遞迴輸出,無法不讓頭節點輸出,遞迴效能差,不建議使用 50 //其實也能讓頭節點不輸出,將以下程式碼重寫一個方法,將head.next傳入 51 // HeroNode temp = head; 52 // if(temp!=null){ 53 // printRearToFront(temp.next); 54 // System.out.println(temp); 55 // } 56 //方式二:使用棧Stack,利用棧的特性來寫 57 if(head.next == null){ 58 return; 59 } 60 Stack<HeroNode> stack = new Stack<>(); 61 HeroNode temp = head.next; 62 while (temp!=null){ 63 stack.add(temp); 64 temp=temp.next; 65 } 66 while (stack.size()>0){ 67 System.out.println(stack.pop()); 68 } 69 } 70 public static void main(String[] args) { 71 SingleLinkedList linkedList = new SingleLinkedList(); 72 linkedList.addNodeByNo2(new HeroNode(0,"張三")); 73 linkedList.addNodeByNo2(new HeroNode(1,"李四")); 74 linkedList.addNodeByNo2(new HeroNode(4,"王五")); 75 linkedList.addNodeByNo2(new HeroNode(2,"趙六")); 76 linkedList.addNodeByNo2(new HeroNode(3,"吳七")); 77 linkedList.show(); 78 System.out.println("倒數第k個節點:"); 79 System.out.println(getReciprocalK(linkedList.getHead(),5)); 80 linkedList.show(); 81 System.out.println("反轉單鏈表:"); 82 reverseNode(linkedList.getHead()); 83 linkedList.show(); 84 System.out.println("從後往前列印單鏈表"); 85 printRearToFront(linkedList.getHead()); 86 } 87 88 }
View Code