问题描述:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。例如[1,2,3,4]变为[2,1,4,3]
public ListNode changeNode(ListNode root)
{
ListNode pre=null;
ListNode firstChange=root;
ListNode secondChange=root.next;
ListNode res=secondChange;
ListNode res1=root;
while(firstChange!=null&&secondChange!=null)
{
if(pre!=null)
{
ListNode third=secondChange.next;
pre.next=secondChange;
secondChange.next=firstChange;
firstChange.next=third;
firstChange=third;
secondChange=third.next;
pre=firstChange;
}else
{
secondChange.next=firstChange;
firstChange.next=third;
firstChange=third;
secondChange=third.next;
pre=firstChange;
}
}
return?res==null:res1?res;
}
递归的方式求解:
public void exchangeNode(TreeNode root,TreeNode parent)
{
if(root==null||root.next==null){return;}
ListNode nextparent=root;
ListNode nextRoot=root.next.next;
ListNode second=root.next;
if(parent!=null)
{
parent.next=second;
second.next=root;
root.next=nextRoot;
}
exchangeNode(nextRoot,nextParent);
}
public TreeNode? ExchangeNode(TreeNode root)
{
ListNode res=root.next;
if(res==null){return root;}
exchangeNode(root,null);
return res;
}