题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。链表结点定义如下:
struct ListNode{
int m_nKey;
ListNode* m_pNext;
}
相当于有两条链表,从一条链表复制到另外一条链表中。
测试用例:
1)输入的链表头指针是null;
2)输入的链表只有一个结点;
3)输入的链表有多个结点。
代码实现:
package com.yyq; /**
* Created by Administrator on 2015/9/13.
*/
public class ReverseList {
public static ListNode reverseList(ListNode pHead) {
ListNode pReversedHead = null;
ListNode pNode = pHead;
ListNode pPrev = null;
ListNode pNext = null;
while (pNode != null) {
pNext = pNode.getM_pNext(); //注意这里面的逻辑,如果把这句话放在while最后的话,会产生空指针异常
if (pNext == null) {
pReversedHead = pNode;
}
pNode.setM_pNext(pPrev);
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
} public static void printList(ListNode pListHead) {
if (pListHead == null)
return;
ListNode pNode = pListHead;
while (pNode != null) {
System.out.print(pNode.getM_nValue() + " ");
pNode = pNode.getM_pNext();
}
System.out.println();
} // ====================测试代码====================
public static ListNode Test(ListNode pHead) {
System.out.println("The original list is: ");
printList(pHead);
ListNode pReversedHead = reverseList(pHead);
System.out.println("The reversed list is: ");
printList(pReversedHead); return pReversedHead;
} // 输入的链表有多个结点
public static void Test1() {
ListNode pNode1 = new ListNode(1);
ListNode pNode2 = new ListNode(2);
ListNode pNode3 = new ListNode(3);
ListNode pNode4 = new ListNode(4);
ListNode pNode5 = new ListNode(5);
ListNode pNode6 = new ListNode(6); pNode1.setM_pNext(pNode2);
pNode2.setM_pNext(pNode3);
pNode3.setM_pNext(pNode4);
pNode4.setM_pNext(pNode5);
pNode5.setM_pNext(pNode6); Test(pNode1);
pNode1 = null;
} // 输入的链表只有一个结点
public static void Test2() {
ListNode pNode1 = new ListNode(1);
Test(pNode1);
pNode1 = null;
} // 输入空链表
public static void Test3() {
Test(null);
} public static void main(String[] args) {
Test1();
Test2();
Test3();
}
}
输出结果:
The original list is:
1 2 3 4 5 6
The reversed list is:
6 5 4 3 2 1
The original list is:
1
The reversed list is:
1
The original list is:
The reversed list is: