如何将第一个节点替换为Java链表中的最后一个节点

时间:2017-12-30 11:57:56

标签: java data-structures linked-list

您好,我想将第一个节点替换为最后一个节点,将最后一个节点替换为第一个节点

这是我的代码,但是出了点问题:有什么帮助吗?

public void replaceNode() {

    Node firstNode = head.next;
    Node lastNode = null;

    location = head;
    while (head != null) {
        location = location.next;
        predLocation = location;
        lastNode = location;
    }

    head.next = lastNode;
    lastNode.next = head.next.next;

    firstNode.next = null;
    predLocation.next = firstNode;

}

2 个答案:

答案 0 :(得分:0)

尝试以下简单代码..

import java.util.Scanner;

public class swapHeadTail{

static llistNode insert(llistNode H,int data){
    llistNode tmp = new llistNode();
    tmp.data=data;
    tmp.next=null;
    if(H==null)
        return tmp;
    llistNode curr = new llistNode();
    curr = H;
    while(curr.next != null)
        curr = curr.next;
    curr.next = tmp;
    return H;
}

public static void main(String[] args) {
    llistNode H = new llistNode();
    Scanner in = new Scanner(System.in);
    llistNode tmp =new llistNode();

    H=null;
    do{
        System.out.print("Enter data:");
        H=insert(H,in.nextInt());
        System.out.print("Enter 1 to continue: ");
    }while (in.nextInt()==1);

    tmp = H;
    while(tmp != null){
        System.out.print(tmp.data+"\t");
        tmp = tmp.next;
    }
    System.out.println();

    llistNode head = new llistNode();
    llistNode headNext = new llistNode();
    llistNode tailPrev = new llistNode();
    llistNode tail = new llistNode();

    head = H;
    headNext = H.next;
    tailPrev = H;
    while(tailPrev.next.next != null)
        tailPrev=tailPrev.next;
    tail = tailPrev.next;
    if ((tailPrev == head)&&(headNext == tail)){
        head.next = null;
        tail.next = head;
    }
    else{
        tmp = head;
        tmp.next = null;
        tailPrev.next = tmp;
        tail.next=headNext;
    }
    H=tail;
    tmp = H;
    while(tmp != null){
        System.out.print(tmp.data+"\t");
        tmp = tmp.next;
    }

  }
 }

参考:http://rawjava.blogspot.in/2015/04/java-program-to-swap-head-and-tail-of.html

答案 1 :(得分:0)

只需更改两个节点之间的值而不更改链接。如果它是不可变的,那么可以使用下面的代码。

public void replaceNode(ListNode head) {
            ListNode firstNode = head.next;
            ListNode tempNode = head;
            ListNode preLastNode = null;
            while(tempNode.next !=null) {
                preLastNode=tempNode;
                tempNode=tempNode.next;
            }
            head.next=preLastNode.next;
            head.next.next=firstNode.next;
            preLastNode.next=firstNode;
            preLastNode.next.next=null;
        }