import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode oddEvenList (ListNode head) {
// write code here
//如果head为空,返回空就行
if (head == null) {
return null;
}
// //如果head.next域为自身,返回的就是head
if (head.next == null) {
return head;
}
//定义一个cur指针指向头结点的下一个结点(偶数),另一个pre指针指向头结点(奇数)
ListNode cur = head.next;
ListNode pre = head;
//定义一个preHead指针指向偶结点的头结点
ListNode curHead = cur;
//让cur遍历到链表的尾结点
while (cur != null && cur.next != null) {
/*
pre.next的域存放的必须为奇结点的地址,
pre指向下一个奇结点
*/
pre.next = cur.next;
pre = pre.next;
/*
pre的位置是奇结点,cur.next的域必须存放偶结点的地址,
pre.next一定是偶结点,cur指向下一个偶结点
*/
cur.next = pre.next;
cur = cur.next;
}
/*
整个链表遍历完,pre指向的就是最后一个奇结点,
cur遍历完指向就是最后一个偶结点,
但是preHead指针的指向为偶结点的头结点,
让奇结点的next域存放偶结点
*/
pre.next = curHead;
//因为头结点自始到终没有动过,返回头结点
return head;
}
}
BM14 链表的奇偶重排(双指针遍历法)
最新推荐文章于 2023-08-14 17:21:09 发布