328. Odd Even Linked List

原题

  • 题目描述:把一个链表奇数节点先放一起,然后再把偶数节点穿起来
  • 思路:定义两个指针,各自走两步,改变相应的指针域即可,特别注意循环条件
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if((head==null)||(head.next==null)){
            return head;
        }
        ListNode odd=head;
        ListNode temp=head.next;
        ListNode even=head.next;
        while(even!=null && even.next!=null){
            odd.next=odd.next.next;
            even.next=even.next.next;
            odd=odd.next;
            even=even.next;
        }
        odd.next=temp;
        return head;
    }
}

你可能感兴趣的:(LeetCode题解,LinkList,medium)