Exam questions 2 public static int get List
Exam questions 2
public static int get. List. Length(Node head){ int counter = 0; while (head != null){ head = head. get. Next(); counter++; } return counter; } public static Node get. NNode(Node head, int n){ while (n > 1){ n--; head = head. get. Next(); } return head; } public static boolean is. Palindrome(Node head){ int len = get. List. Length(head); Node org. Head=head; for (int i=0; i<len/2; i++){ if (head. get. Data() != get. NNode(org. Head, len-i). get. Data()){ return false; } head = head. get. Next(); } return true; }
public static Node reverse. List(Node head){ Node prev = null; while (head != null){ Node link = head. get. Next(); head. set. Next(prev); prev = head; head = link; } return prev; } public static boolean is. Palindrome 1(Node head){ int len = get. List. Length(head); Node link = get. NNode(head, len/2); Node head 2 = reverse. List(link); for (int i=0; i<len/2; i++){ if (head. get. Data() != head 2. get. Data()){ return false; } head = head. get. Next(); head 2 = head 2. get. Next(); } return true; }
public static void swap(int[] arr, int idx 1, int idx 2){ int temp = arr[idx 1]; arr[idx 1] = arr[idx 2]; arr[idx 2]=temp; } public static void sort. Flats(int[] flats){ int t 1 = -1; int t 2 = 0; int t 3 = flats. length-1; int t 4 = flats. length; while (t 2 <= t 3){ switch (flats[t 2]){ case 1: t 1++; swap(flats, t 1, t 2); t 2++; break; case 2: t 2++; break; case 3: swap(flats, t 2, t 3); t 3 --; break; case 4: t 4 --; swap(flats, t 3, t 4); if (t 2<t 3){ swap(flats, t 2, t 4); } t 3 --; break; } } }
- Slides: 19