调整数组顺序使奇数位于偶数前面
class Solution:
def exchange(self, nums):
list1=[]
list2=[]
for i in nums:
if(i%2==0):
list1.append(i)
else:
list2.append(i)
return list1+list2
链表中倒数第k个节点
思路:一个引用指向头结点,另一个指向第k个节点,然后一起往后移动,当后者到达尾部结点时,返回前者即可
class ListNode
{
int val;//存储元素
ListNode next;
public ListNode(int val)
{
this.val=val;
next=null;
}
public static ListNode Create(int[] val)
{
ListNode head=new ListNode(0);
ListNode T=head;
for(int i:val)
{
T.next=new ListNode(i);
T=T.next;
}
return head;
}
}
public class Solution {
public static int count=0;
public ListNode getKthFromEnd(ListNode head,int k)
{
int i=0;
ListNode rear=head;
while(rear!=null)
{
if(i==k)
head=head.next;
rear=rear.next;
if(i<k)
i+=1;
}
return head;
}
public static void main(String[] args)
{
int[] val= {1,2,3,4,5};
ListNode head=ListNode.Create(val);
Solution ss=new Solution();
ListNode K=ss.getKthFromEnd(head, 1);
System.out.println(K.val);
}
}