将单链表l1拆成二个链表,其中以l1为头的链表保持原来向后的链接,一个链表的头为l2,其链接方向与l1相反,l1包含原链表的奇数序号的结点,l2包含原链表的偶数序列的结点,通过main函数完成函数调用。
时间: 2023-04-28 11:02:02 浏览: 94
可以按照以下步骤将单链表l1拆成两个链表:
1. 创建两个新的链表头节点l1_new和l2_new,分别表示原链表的奇数序号节点和偶数序号节点。
2. 遍历原链表l1,将奇数序号节点插入到l1_new链表的末尾,将偶数序号节点插入到l2_new链表的末尾。
3. 最后,将l2_new链表反转,使其链接方向与l1相反。
具体实现可以参考以下代码:
// 定义链表节点结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 将单链表l1拆成两个链表
void splitList(ListNode* l1, ListNode* &l1_new, ListNode* &l2_new) {
ListNode *p1 = l1, *p2 = NULL, *p3 = NULL;
l1_new = new ListNode();
l2_new = new ListNode();
p2 = l1_new;
p3 = l2_new;
int count = 1;
while (p1 != NULL) {
if (count % 2 == 1) {
p2->next = new ListNode(p1->val);
p2 = p2->next;
} else {
p3->next = new ListNode(p1->val);
p3 = p3->next;
}
p1 = p1->next;
count++;
}
// 反转l2_new链表
ListNode *prev = NULL, *curr = l2_new->next, *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
l2_new->next = prev;
}
// 测试函数
int main() {
ListNode *l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(3);
l1->next->next->next = new ListNode(4);
l1->next->next->next->next = new ListNode(5);
ListNode *l1_new = NULL, *l2_new = NULL;
splitList(l1, l1_new, l2_new);
// 输出l1_new链表
ListNode *p = l1_new->next;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
// 输出l2_new链表
p = l2_new->next;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
return ;
}
阅读全文