一、将单链表的奇数节点和偶数节点分别排在一起,奇数偶数指的是节点编号;保持奇数节点和偶数节点的相对顺序;
输入:1->2->3->4->5->null输出:1->3->5->2->4->null
思路:
* 1.创建两个链表,奇数链表和偶数链表;
* 2.遍历原链表,将奇数节点赋值给奇数链表,偶数节点赋值给偶数链表;
* 3.将偶数节点跟在奇数节点后面;
public ListNode oddEvenList(ListNode head) {
if (head == null) {
return null;
}else if (head.next == null) {
return head;
}
ListNode odd = new ListNode(0);
ListNode oddCur = odd;
ListNode even = new ListNode(0);
ListNode evenCur = even;
while (head != null) {
int i = 0;
if (i % 2 != 0) {
oddCur.next = new ListNode(head.val);
oddCur = oddCur.next;
}else {
evenCur.next = new ListNode(head.val);
evenCur = evenCur.next;
}
head = head.next;
}
oddCur.next = even.next;
return odd.next;
}
二、给定一个链表和一个整数k,将链表分成两部分,比k小的放在左边,比k大的放在右边;并且左右两部分各自的相对顺序不变。
* 输入:k=5, head:1->9->7->3->6->5->2* 输出:1->3->5->2->9->7->6
public class OddEvenList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ListNode head = null;
ListNode node = null;
int k = scanner.nextInt();
int i = 7;
// while (scanner.hasNextInt()) {
while (i-- != 0) {
int val = scanner.nextInt();
if (head == null) {
node = new ListNode(val);
head = node;
}else {
node.next = new ListNode(val);
node = node.next;
}
}// end while
head = partition(head, k);
if (head != null) {
System.out.print(head.val);
head = head.next;
while (head != null) {
System.out.print(",");
System.out.print(head.val);
head = head.next;
}
}
System.out.println();
}
public ListNode oddEvenList(ListNode head) {
if (head == null) {
return null;
}else if (head.next == null) {
return head;
}
ListNode odd = new ListNode(0);
ListNode oddCur = odd;
ListNode even = new ListNode(0);
ListNode evenCur = even;
while (head != null) {
int i = 0;
if (i % 2 != 0) {
oddCur.next = new ListNode(head.val);
oddCur = oddCur.next;
}else {
evenCur.next = new ListNode(head.val);
evenCur = evenCur.next;
}
head = head.next;
}
oddCur.next = even.next;
return odd.next;
}
/**
* 给定一个链表和一个整数k,将链表分成两部分,比k小的放在左边,比k大的放在右边;并且左右两部分各自的相对顺序不变。
* @param head
* @param k
* @return
*/
/**
* 输入:k=5, head:1->9->7->3->6->5->2
* 输出:1->3->5->2->9->7->6
*/
public static ListNode partition(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode small = new ListNode(0);
ListNode smallCur = small;
ListNode large = new ListNode(0);
ListNode largeCur = large;
while (head != null) {
if (head.val <= k) {
smallCur.next = new ListNode(head.val);
smallCur = smallCur.next;
}else {
largeCur.next = new ListNode(head.val);
largeCur = largeCur.next;
}
head = head.next;
}
smallCur.next = large.next;
return small.next;
}
}