您的位置:首页 > 编程语言 > Java开发

java之链表反转

2015-06-05 16:36 507 查看
题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后的头节点,链表的定义如下:

class LNode { // 单链表的存储结构
int value;
LNode next;

public LNode() {
}

public LNode(int value) {
this.value = value;
this.next = null;
}

public LNode(int value, LNode next) {
this.value = value;
this.next = next;
}
}反转的代码:
package LinkList;

public class ReverseListMain {
public LNode head = new LNode();// 创建空的头节点

public void insertHead(int value) { // 插入节点,从头开始
LNode link = new LNode(value); // 创建一个带value值的节点
link.next = head.next;
head.next = link;
}

public LNode ReverseList(LNode node) {
LNode pReverseList = null;
LNode pNode = node;
LNode pPrev = null;
while (pNode != null) {
LNode pNext = pNode.next; //将下一个结点赋给pNext
if (pNext == null)//如果pNext为空
pReverseList = pNode;//就可以得到最后一个结点
pNode.next = pPrev;//将链表从pNode结点断开
pPrev = pNode;//将pNode.next结点指向pNode的结点
pNode = pNext;

}

return pReverseList;//返回反转后的头结点
}

public void print(LNode node) {
LNode p = node;
while (p != null) {
System.out.print(p.value + " ");
p = p.next;

}
}

public static void main(String[] args) {
ReverseListMain listMain = new ReverseListMain();
for (int i = 1; i < 10; i++) {
listMain.insertHead(i);
}
listMain.print(listMain.head.next);
LNode node = listMain.ReverseList(listMain.head.next);
System.out.println();
listMain.print(node);

}

}


结果为:
9 8 7 6 5 4 3 2 1 

1 2 3 4 5 6 7 8 9 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: