LintCode:511. 交换链表中的两个节点

分析:

  • 首先,因为头结点也有可能被交换,所以需要在头结点之前创建一个新结点,然后连接到现有的链表之前。
  • 新建指针pre1和pre2作为v1和v2的前结点,扫描链表,若pre1或者pre2为空,说明未找到v1或v2。
  • 如果pre1和pre2相邻,即pre1.next=pre2,则交换,使得pre1在前pre2在后。
  • 讨论两种情况,分别为pre1.next==pre2和pre1与pre2不相邻的情况。
public ListNode swapNodes(ListNode head, int v1, int v2) {
        // write your code here
        ListNode newhead=new ListNode(-1);
        newhead.next=head;
        ListNode pre1=null,pre2=null;
        ListNode cur=newhead;
        while(cur.next!=null){
            if(cur.next.val==v1){
                pre1=cur;
            }else if (cur.next.val==v2){
                pre2=cur;
            }
            cur=cur.next;
        }
        if(pre1==null || pre2==null)    return head;   // 未找到结点v1和v2
        //使v1和v2两节点在相邻时保持v1在前v2在后
        if(pre2.next==pre1){
            ListNode t=pre2;
            pre2=pre1;
            pre1=t;
        }

        ListNode node1=pre1.next;
        ListNode node2=pre2.next;
        ListNode node2Next=node2.next;
        if(pre1.next==pre2){
            pre1.next=node2;
            node2.next=node1;
            node1.next=node2Next;
        }else{
            pre1.next=node2;
            node2.next=node1.next;
            pre2.next=node1;
            node1.next=node2Next;
        }
        return newhead.next;
    }

猜你喜欢

转载自blog.csdn.net/qq_27139155/article/details/80415857