示例:在链接列表上调用的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;
}
主();
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
我的代码中出了什么问题,为什么它显示列表是空的
答案 0 :(得分:0)
这可以通过简单直接的方法将列表的“头部”链接到其“尾部”并更新头部来实现。
下面的函数返回List的更新头部。(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;
}