将链表节点顺序重组:奇数节点在前,偶数节点在后;
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(head==NULL)
return head;
ListNode* end_odd=head;
ListNode* cur_even=head->next;
while(end_odd&&cur_even)
{
ListNode *next_odd=cur_even->next;
if(next_odd)
{
cur_even->next=next_odd->next;
//end_odd->next=next_odd;
//next_odd->next=cur_even;
next_odd->next=end_odd->next;
end_odd->next=next_odd;
end_odd=end_odd->next;
cur_even=cur_even->next;
}
else
break;
}
return head;
}
};
本文介绍了一种链表操作算法,该算法将链表中的节点按奇偶顺序重新排列,确保所有奇数位置的节点位于偶数位置的节点之前。通过遍历链表并调整指针连接的方式实现这一目标。
5万+

被折叠的 条评论
为什么被折叠?



