示例:在链表上调用 cut 方法:
f{1, 2, 3, 4, 5, 6, 7}
将返回链接列表:
f{5,6, 7, 1, 2, 3, 4}
LinkList Cut() 方法
public static LinkList Cut(LinkList x) {
LinkList front = new LinkList();
LinkList back = new LinkList();
while(!x.isEmpty){
front.insertLast(x.removeFirst().data);
if(!x.isEmpty){
back.insertFirst(x.removeLast().data);
}
}
while(!back.isEmpty){
front.insertFirst(back.removeLast().data);
}
return front;
}
第一个和最后一个、删除和插入方法。
public void insertFirst(int data){
start = new Node(0);
if(start == null){
System.out.println("list is empty if");
}else{
start.link = head.link;
start.data = 20;
head.link = start;
}
}
public void insertLast(int data) {
start = new Node(0);
if(start == null){
System.out.println("List is empty il");
}else{
ptr = head;
while(ptr.link != null){
ptr = ptr.link;
}
ptr.link = start;
start.data = 20;
}
}
public Node removeFirst(){
ptr = head.link;
if(ptr == null){
System.out.println("The list is empty");
}else{
ptr1 = ptr.link;
head.link = ptr1;
}
return ptr;
}
public Node removeLast() {
ptr = head;
if(ptr.link == null)
{
System.out.println("List is Empty rl");
}else{
while(ptr.link != null){
ptr1 = ptr;
ptr = ptr.link;
}
ptr1.link = null;
}
return ptr;
}
main();
LinkList list = new LinkList();
LinkList.head = new Node(1);
LinkList.head.link = new Node(2);
LinkList.head.link.link = new Node(3);
LinkList.head.link.link.link = new Node(4);
LinkList.head.link.link.link.link = new Node(5);
LinkList.head.link.link.link.link.link = new Node(6);
LinkList.head.link.link.link.link.link.link = new Node(7);
System.out.println("Link List Element: ");
list.printList(head);
list.Cut(list);
System.out.println("");
System.out.println("Cut Half Link List Element: ");
list.printList(head);
输出。
Link List Element:
1
2
3
4
5
6
7
The list is empty
我的代码有什么问题,为什么显示列表为空
最佳答案
这可以通过将列表的“头”链接到其“尾部”并更新头的简单而直接的方法来实现。
下面的函数返回更新后的列表头。(C++)。
Node *CutTheList(Node *head)
{
int sizeList=0; // Contains the size of the List
Node *tracker=head; // temporary tracker
while(tracker!=NULL){ sizeList++; tracker=tracker->next;} // Counts the Size of the List
tracker=head;
while(tracker->next!=NULL){tracker=tracker->next;} // Assigns the head to tail.
tracker->next=head;
int sizehalf=sizeList/2; //Size of the halved List.
tracker=head;
while(--sizehalf){ tracker=tracker->next; } //Update the head
head=tracker->next;
tracker->next=NULL;
return head;
}
关于java - 编写一个方法 cut(LinkList x),将列表 x 分成两个(大致)相等的两半,并将后半部分放在前半部分的前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39966115/