我在尝试将链表分成两半时遇到一些问题。举例来说,我的链表是 2,3,5,6,7。第一个分割链表应包含 2,3,5,第二个分割链表应包含 6,7。
我还没有真正拿出代码,因为我仍然需要伪代码方面的一些帮助。
int check = size%2
if even
int half = size/2
while(ctrFront < half)
front.insertNode; ctrFront++; update head pointer;
while(ctrBack < half)
back.insertNode; ctrBack++; update head pointer;
if odd
int half = size/2 round up
while(ctrFront < half + 1)
front.insertNode; ctrFront++; update head pointer;
while(ctrBack < half)
back.insertNode; ctrBack++; update head pointer;
我不确定这是否是正确的方法,因为逻辑似乎有点错误。有什么指南吗?
提前致谢。
最佳答案
构造两个列表。弹出源列表直到其为空,将每个项目交替推送到新列表上。将源列表的头指针重置为新列表之一。
就这样,很简单:
linkedList *newList1=NULL;
linkedList *newList2=NULL;
while(true){
node *temp;
node=listPop(&sourceList);
if(temp==NULL) break;
listPush(&newList1,temp);
temp=listPop(&sourceList);
if(temp==NULL) break;
listPush(&newList2,temp);
};
关于c - 将链表拆分为半个 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33452460/