1、调整数组顺序使奇数位于偶数前面
1.1 题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
1.2 题解
1.2.1 双指针
public int[] exchange(int[] nums) {
if (nums.length <= 1)
return nums;
int i = 0, j = nums.length - 1;
while (i < j) {
while (nums[i] % 2 != 0 && i < j)//找到偶数
i++;
while (nums[j] % 2 == 0 && i < j)//找到奇数
j--;
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return nums;
}
2、链表中倒数第k个节点
2.1 题目描述:
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
2.2 题解
2.2.1 快慢指针
public ListNode getKthFromEnd(ListNode head, int k) {
if(head==null)
return null;
int length=0;
ListNode fast=head;//快指针
ListNode slow=head;//慢指针
while(fast!=null){
fast=fast.next;
length++;
if(length>k){ //慢指针可以开始移动,快慢指针差k个节点
slow=slow.next;
}
}
if(length<k)//当快指针到达最后,慢指针指向倒数第k个
return null;
return slow;
}
3、反转链表
3.1 题目描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
3.2 题解
3.2.1 新建一条链表存储反转后的链表
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
ListNode newHead =new ListNode(-1);
ListNode index =head;
ListNode cur=index;
ListNode next=null;
while(cur!=null){
next=cur.next;//找到原链表的第二个节点
cur.next=newHead.next; //原链表的第一个节点的下一个节点指向新链表的第一个节点
index.next=next;//原链表头指针指向原链表的第二个节点
newHead.next=cur;//新链表的头指针指向原第一个节点
cur=next;//循环条件
}
return newHead.next;
}
3.2.2 递归,在原链表上进行更改
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode cur =reverseList(head.next);//将返回原链表的最后节点
head.next.next =head;
head.next=null;
return cur;
}