标签:
而翻转后,C无法再指向D会出现链表断裂;故在反转前要注意保留D,即C.pNext;
class ListNode
{
int pValue;
ListNode pNext;
public ListNode(int pValue,ListNode pNext)
{
this.pNext = pNext;
this.pValue = pValue;
}
}
public class LinkListEx {
public ListNode reverse(ListNode pHead)
{
if (pHead == null || pHead.pNext == null)
return pHead;
ListNode pNodeA = pHead;
ListNode pNodeB = pHead.pNext;
ListNode pNodeC = pHead.pNext.pNext;
pHead.pNext = null;
while(pNodeB != null)
{
pNodeB.pNext = pNodeA;
pNodeA = pNodeB;
pNodeB = pNodeC;
if (pNodeB != null)
pNodeC = pNodeB.pNext;
}
return pNodeA;
}
public void delete(ListNode pNode)
{
if (pNode == null || pNode.pNext == null)
return;
//由于题设中简化了难度,假设pNode既非头结点,也非尾节点,故其实不许进行边界判断
ListNode pNext = pNode.pNext;
pNode.pValue = pNext.pValue;
pNode.pNext = pNext.pNext;
}
public static void main(String[] args)
{
ListNode p5 = new ListNode(5, null);
ListNode p4 = new ListNode(4, p5);
ListNode p3 = new ListNode(3, p4);
ListNode p2 = new ListNode(2, p3);
ListNode p1 = new ListNode(1, p2);
LinkListEx linkListEx = new LinkListEx();
// linkListEx.print(linkListEx.reverse(p1));
linkListEx.delete(p3);
linkListEx.print(p1);
}
public void print(ListNode pHead)
{
while(pHead != null)
{
System.out.println(pHead.pValue + "==>");
pHead = pHead.pNext;
}
}
}
标签:
原文地址:http://blog.csdn.net/woliuyunyicai/article/details/46483305