leetcode 328.奇偶链表(medium)

题目:

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

示例:1.输入: 1->2->3->4->5->NULL   

             输出: 1->3->5->2->4->NULL

          2.输入: 2->1->3->5->6->4->7->NULL    

            输出: 2->3->6->7->1->5->4->NULL

思路:奇链表放head1中,偶链表放head2中,再将偶链表接到奇链表后面

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
      if(head==NULL||head->next==NULL||head->next->next==NULL) return head;
      ListNode *head1=head;
      ListNode *head2=head->next;
      ListNode *p1=head1;
      ListNode *p2=head2;
      
      p1->next=p2->next;
      p2->next=NULL;
      p1=p1->next;
      while(p1!=NULL&&p1->next!=NULL)
      {
          ListNode *temp=p1->next;
          p1->next=temp->next;
          temp->next=NULL;
          p2->next=temp;
          p2=p2->next;
          if(p1->next==NULL) continue;
          p1=p1->next;
      }
      p1->next=head2;
      return head1;
    }
};

猜你喜欢

转载自blog.csdn.net/lyychlj/article/details/104689782