Java中连续链表的反向子部分
我试图反转单链表的一个子部分,其中该子部分是一组连续的偶数元素,由列表的末尾或奇数元素包围 到目前为止,我知道如何反转链表,但我不知道如何检查元素是否为奇数或是否位于末尾Java中连续链表的反向子部分,java,linked-list,Java,Linked List,我试图反转单链表的一个子部分,其中该子部分是一组连续的偶数元素,由列表的末尾或奇数元素包围 到目前为止,我知道如何反转链表,但我不知道如何检查元素是否为奇数或是否位于末尾 Node reverse(Node head) { // Write your code here if(head == null) return null; Node prev = null; Node curr = head; Node next = null; wh
Node reverse(Node head) {
// Write your code here
if(head == null) return null;
Node prev = null;
Node curr = head;
Node next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
范例
输入:
列表=[1,2,8,9,12,16]
输出:
[1,8,2,9,16,12]
本例中的子部分是2,8和12,16“如果在末尾”,您已经知道这一点。如果
next
为空,则节点是列表中的最后一个节点,即它位于末尾。“如果元素为奇数”真的吗?你还没有在网上找到任何关于如何检查一个值是奇数还是偶数的例子。更可能的情况是,你甚至没有尝试过,所以“向下提问”投票是因为缺乏研究。只需检查模是1还是0。如果是1,那是个奇数。如果是0,则为偶数。我同意安德烈亚斯的观点。在你提问之前,你应该做更多的研究。最好在你的答案周围添加一些细节/解释。
Node reverse(Node head) {
if(head == null) return null;
Node curr = head;
Node next = null;
Node prev = null;
while(curr!=null && curr.data%2==0) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
if(curr!=head) {
head.next = curr;
curr = reverse(curr);
return prev;
} else {
head.next = reverse(head.next);
return head;
}
}
class LinkedList {
Node head;
Node curr = head;
Node next = null;
Node prev = null;
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
void pairWiseSwap()
{
Node temp = head;
while (temp != null && temp.next!=null) {
int k = temp.data;
int j = temp.next.data;
if(k%2==0 && j%2==0) {
temp.data=j;
temp.next.data=k;
temp=temp.next.next;
continue;
}
temp = temp.next;
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push(16);
llist.push(12);
llist.push(9);
llist.push(8);
llist.push(2);
llist.push(1);
System.out.println("Linked List before calling pairWiseSwap() ");
llist.printList();
llist.pairWiseSwap();
System.out.println("Linked List after calling pairWiseSwap() ");
llist.printList();
}
}